react runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
95%Fix Rate
88%Confidence
1Evidence
2024-01-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
React 18.2.0 active
React 19.0.0 active
React 16.8.0 active

Root Cause

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

中文

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

Official Documentation

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

Workarounds

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

中文步骤

  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]);`

Dead Ends

Common approaches that don't work:

  1. 95% fail

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

  2. 90% fail

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