react runtime_error ai_generated true

错误:无法在现有的状态转换期间更新(例如在 `render` 中)。渲染方法应是 props 和 state 的纯函数。

Error: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

ID: react/cannot-update-during-existing-state-transition

其他格式: JSON · Markdown 中文 · English
95%修复率
88%置信度
1证据数
2024-01-05首次发现

版本兼容性

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

根因分析

在 render 方法或渲染阶段的生命周期中同步触发了状态更新(setState),违反了 React 关于 render 必须是纯函数的规则。

English

A state update (setState) is triggered synchronously inside the render method or a render-phase lifecycle, violating React's rule that render must be pure.

generic

官方文档

https://react.dev/learn/keeping-components-pure

解决方案

  1. Move the state update to a useEffect or event handler: instead of `render() { setState(...); }`, use `useEffect(() => { setState(...); }, []);`
  2. If the state update depends on props change, use `useEffect` with the relevant prop as dependency: `useEffect(() => { setState(...); }, [prop]);`

无效尝试

常见但无效的做法:

  1. 95% 失败

    Any synchronous state update during render is forbidden, regardless of location.

  2. 90% 失败

    The error is thrown by React internally and cannot be caught by user try-catch.