react runtime_error ai_generated true

错误:超过最大更新深度。当组件在 useEffect 内部调用 setState,但 useEffect 没有依赖数组,或者某个依赖在每次渲染时都发生变化时,可能会发生这种情况。

Error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

ID: react/state-update-in-effect-without-deps

其他格式: JSON · Markdown 中文 · English
88%修复率
90%置信度
1证据数
2023-08-22首次发现

版本兼容性

版本状态引入弃用备注
React 18.2.0 active
React 17.0.2 active

根因分析

带有状态更新的 useEffect 要么缺少依赖数组(每次渲染后运行),要么有一个在每次渲染时都会发生变化的依赖(例如新的对象/函数),从而导致无限循环。

English

A useEffect with a state update either lacks a dependency array (runs after every render) or has a dependency that mutates on every render (e.g., a new object/function), causing an infinite loop.

generic

官方文档

https://react.dev/reference/react/useEffect#updating-state-based-on-previous-state

解决方案

  1. Provide a proper dependency array with stable values. If the state update depends on previous state, use the functional update form: setState(prev => prev + 1).
  2. If the effect needs to react to a changing value, ensure that value is memoized with useMemo or useCallback to maintain referential stability.

无效尝试

常见但无效的做法:

  1. 50% 失败

    If the effect needs to react to prop or state changes, an empty array makes it run only once, potentially missing updates and causing stale data.

  2. 85% 失败

    Inline functions/objects are new references each render, so the effect runs every time, defeating the purpose.