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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://react.dev/reference/react/useEffect

解决方案

  1. 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
  2. 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
  3. If the effect depends on props or state that change, use useReducer to manage complex state transitions and avoid direct setState in effects.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Does not address the root cause; the useEffect still runs without dependencies, triggering setState on every render.

  2. 90% 失败

    Causes an infinite loop during render because setState triggers a re-render immediately.

  3. 70% 失败

    The condition may still be true on every render, or the effect runs on every render anyway, leading to the same loop.