解决 Node.js 报错 Maximum call stack size exceeded 栈溢出
分析 Node.js 深层递归或循环引用序列化报 RangeError: Maximum call stack size exceeded 的排查与尾调用循环重构方案。
问题现象
Node.js 应用执行递归或深层对象操作时突然崩溃闪退:
RangeError: Maximum call stack size exceeded
at cloneDeep (/app/utils.js:42:15)
at cloneDeep (/app/utils.js:45:20)
... (repeated thousands of times)
触发根因
- 递归函数没有正确的退出基准条件,陷入了死循环调用。
- 在深层拷贝或序列化(如
JSON.stringify或自定义 deepClone)时,对象内部存在循环引用(Circular References)。
解决步骤与操作命令
步骤一:使用 WeakMap 防止对象循环引用递归死循环
编写深拷贝时记录已访问对象:
function safeDeepClone(obj, hash = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (hash.has(obj)) return hash.get(obj); // 命中循环引用直接返回
let copy = Array.isArray(obj) ? [] : {};
hash.set(obj, copy);
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
copy[key] = safeDeepClone(obj[key], hash);
}
}
return copy;
}
步骤二:将深层树遍历递归改写为迭代循环(显式栈/队列)
function traverse(root) {
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
if (!node) continue;
// 处理当前节点
if (node.children) stack.push(...node.children);
}
}
验证确认
在包含自引用的大型对象上运行测试: 代码顺畅完成拷贝或遍历并平稳返回,未再抛出 Maximum call stack size exceeded。


