typescript 中 rangeerror: maximum call stack size exceeded 错误-ag捕鱼王app官网

typescript 中 rangeerror: maximum call stack size exceeded 错误

作者:迹忆客 最近更新:2022/12/29 浏览次数:

rangeerror: maximum call stack size exceeded”当一个函数被调用太多次以至于调用超过调用堆栈限制时发生。 要解决错误,需要追查原因或指定必须满足的基本情况才能退出递归。

下面是产生上述错误的示例

class employee {
  protected _country = 'germany';
  get country(): string {
    // ⛔️ error: rangeerror: maximum call stack size exceeded
    return this.country; // 👈️ should be this._country
  }
}
const emp = new employee();
console.log(emp.country);

typescript 中 rangeerror- maximum call stack size exceeded

上面代码片段中的问题是 country getter 函数不断调用自身,直到调用超过调用堆栈限制。

这是错误如何发生的另一个示例。

function example() {
  example();
}
// ⛔️ error: rangeerror: maximum call stack size exceeded
example();

最常见的错误原因是函数不断调用自身。

要解决示例中使用类 getter 的错误,我们必须通过在属性前加上下划线来访问该属性,而不是调用 getter

class employee {
  protected _country = 'germany';
  get country(): string {
    return this._country;
  }
}

要解决使用函数时的错误,我们必须指定函数停止调用自身的条件。

let counter = 0;
function example(num: number) {
  if (num < 0) {
    return;
  }
  counter  = 1;
  example(num - 1);
}
example(3);
console.log(counter); // 👉️ 4

这次我们检查函数是否在每次调用时使用小于 0 的数字调用。

如果数字小于 0,我们只需从函数返回,这样我们就不会超出调用堆栈限制。

如果传入的值不小于零,我们调用传入的值减1的函数,这使我们朝着满足if检查的情况前进。

递归函数 调用自身直到满足条件。 如果我们的函数中没有满足条件,它将调用自身,直到超过最大调用堆栈大小。

如果我们有一个在某处调用函数的无限循环,我们也可能会遇到此错误。

function sum(a: number, b: number) {
  return a   b;
}
while (true) {
  sum(10, 10);
}

我们的 while 循环不断调用该函数,并且由于我们没有退出循环的条件,我们最终超出了调用堆栈限制。

这与在没有基本条件的情况下调用自身的函数的工作方式非常相似。 如果我们使用 for 循环,情况也是如此。

下面是一个示例,说明如何指定退出循环必须满足的条件。

function sum(a: number, b: number) {
  return a   b;
}
let total = 0;
for (let i = 10; i > 0; i--) {
  total  = sum(5, 5);
}
console.log(total); // 👉️ 100

如果 i 变量等于或小于 0,则不满足 for 循环中的条件,退出循环。

如果我们无法准确跟踪错误发生的位置,请查看浏览器控制台或终端(如果使用 node.js)中的错误消息。

typescript 中 rangeerror- maximum call stack size exceeded

上面的截图显示错误发生在 index.ts 文件的第 5 行。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:typescript

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:typescript

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图