Skip to content

错误: 最大值更新深度 exceeded

错误信息

                最大值更新深度 exceeded. 这个能 happen 当组件 repeatedly calls setState 内部 componentWillUpdate or componentDidUpdate.
              

快速摘要

组件是 stuck in 无限循环的 状态更新 and re-渲染, 通常因为 setState 是 called 期间渲染 or in useEffect 使用错误 dependencies.

为什么发生

  • Called setState directly 期间渲染 (不 in 事件处理函数 or 副作用)

  • useEffect 使用 dependency 那个更改 on 每个渲染

  • useEffect 那个总是 calls setState 不使用条件

  • parent and child 更新每个 other's 状态 in 循环

最小示例

✗ 错误代码
function Component() {
  const [count, setCount] = useState(0);
  setCount(count + 1); // Called during render!
  return <div>{count}</div>;
}
✓ 修复代码
function Component() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Calling setState 期间渲染触发 re-渲染, 哪个 calls setState 再次 — 无限循环. Moving 它到 事件处理函数 breaks cycle.

如何诊断

  • Look for setState calls in 渲染请求体 (不内部事件处理函数)

  • 检查 useEffect dependency 数组 for 值那个更改每个渲染

  • 添加 console.log in 渲染到 see 如何许多次数它 fires

如何修复

  • Move setState 到事件处理函数 or useEffect

  • Fix dependency 数组到 avoid 包含值 那个更改每个渲染

  • 添加条件之前 setState in useEffect 到 avoid 不必要更新

如何预防

  • 从不 call setState 期间渲染

  • Use exhaustive-deps ESLint 规则到 catch dependency issues

  • 是 careful 使用对象/数组 dependencies 那个创建新 引用

相关资源

相关术语

相关课程

  • 状态

    学习到 avoid 无限渲染循环.

← 返回语言