超出最大调用堆栈大小 TypeScript 中的错误 [已修复]

超出最大调用堆栈大小 TypeScript 中的错误

Maximum call stack size exceeded Error in TypeScript

“RangeError: Maximum call stack size exceeded”发生在一个函数被调用太多次以至于调用超过调用堆栈限制时。

要解决错误,请追查原因或指定必须满足的基本情况才能退出递归。

超出最大调用堆栈大小

getter 方法是如何发生错误的

下面是错误如何发生的示例。

索引.ts
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 函数一直调用自身,直到调用超过调用堆栈限制。

常规函数是如何发生错误的

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

索引.ts
function example() { example(); } // ⛔️ Error: RangeError: Maximum call stack size exceeded example();

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

解决使用getter方法时的错误

为了解决使用 getter 方法时的错误,我们必须通过在属性前加上下划线而不是调用 getter 来访问该属性。

索引.ts
class Employee { protected _country = 'Germany'; get country(): string { return this._country; } }

解决使用常规函数时的错误

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

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

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

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

If the passed-in value is not less than zero, we call the function with the
passed in value minus 1.

This keeps us moving toward the case where the if condition is satisfied.

A recursive function calls itself until a condition is met. If there is no condition to be met in your function, it will call itself until the maximum call stack size is exceeded.

# Make sure you don’t have infinite loops

You might also get this error if you have an infinite loop that calls a function
somewhere.

index.ts
function sum(a: number, b: number) { return a + b; } while (true) { sum(10, 10); }
Our while loop keeps calling the function and since we don’t have a condition that would exit the loop we eventually exceed the call stack limit.

This works in a very similar way to a function calling itself without a base
condition. The same would be the case if you were using a for loop.

Here’s an example of how to specify a condition that has to be met to exit the
loop.

index.ts
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

If the i variable is equal to or less than 0, the condition in the for
loop is not satisfied, so we exit the loop.

If you can’t track exactly where your error occurs, look at the error message in
your browser’s console or your terminal (if using Node.js).

超出最大调用堆栈大小

The screenshot above shows that the error occurred on line 5 in the index.ts
file.

# Make sure you don’t load the same script multiple times

如果您多次导入同一个文件,也可能会发生该错误,例如,在同一页面上多次加载 jQuery 脚本。

您可以通过以下方式检查页面上加载了哪些脚本:

  1. 按 ,在浏览器中打开开发者工具F12
  2. Network在浏览器的开发人员工具中选择选项卡。
  3. 正在刷新页面。