TypeScript 中 RangeError: Maximum call stack size exceeded 错误

“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);

上面代码片段中的问题是 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)中的错误消息。