react
runtime_error
ai_generated
true
错误:超过最大更新深度。这可能发生在组件在 useEffect 内调用 setState 而没有依赖数组时
Error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect without a dependency array
ID: react/maximum-update-depth-exceeded-useeffect
95%修复率
90%置信度
1证据数
2023-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17 | active | — | — | — |
| React 18 | active | — | — | — |
| React 19 | active | — | — | — |
根因分析
useEffect 调用 setState 时未指定依赖项,导致渲染 → 副作用 → setState → 渲染的无限循环。
English
A useEffect calls setState without specifying dependencies, causing an infinite loop of render → effect → setState → render.
官方文档
https://react.dev/reference/react/useEffect解决方案
-
Add a dependency array to useEffect with the values that should trigger the effect: useEffect(() => { setCount(count + 1); }, [count]); // Now it only runs when count changes, avoiding infinite loop if count is not updated in a way that causes re-render -
Use the functional update form of setState and an empty dependency array if the effect should run only once: useEffect(() => { setCount(prev => prev + 1); }, []); // Runs once on mount -
If the effect depends on props or state that change, use useReducer to manage complex state transitions and avoid direct setState in effects.
无效尝试
常见但无效的做法:
-
80% 失败
Does not address the root cause; the useEffect still runs without dependencies, triggering setState on every render.
-
90% 失败
Causes an infinite loop during render because setState triggers a re-render immediately.
-
70% 失败
The condition may still be true on every render, or the effect runs on every render anyway, leading to the same loop.