react runtime_error ai_generated true

错误:无效的 Hook 调用。Hook 只能在函数组件的主体中调用。可能的原因:1. React 和渲染器(如 React DOM)版本不匹配;2. 违反了 Hook 规则;3. 同一个应用中有多个 React 副本。

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app.

ID: react/invalid-hook-call-inside-callback

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

版本兼容性

版本状态引入弃用备注
React 16.8+ active
React 17.x active
React 18.x active

根因分析

Hook 在函数组件的顶层之外被调用,例如在回调中、条件性地或在类组件中。也可能因捆绑了多个 React 副本而出现。

English

Hooks are called outside the top-level of a function component, e.g., inside a callback, conditionally, or in a class component. Also occurs when multiple React copies are bundled.

generic

官方文档

https://reactjs.org/warnings/invalid-hook-call-warning.html

解决方案

  1. Ensure all hooks are called at the top level of a function component, not inside loops, conditions, or nested functions. Example: function MyComponent() { const [state, setState] = useState(0); // correct }
  2. Check for duplicate React versions by running npm ls react or yarn why react. If duplicates exist, deduplicate with npm dedupe or use resolutions in package.json.
  3. If using a class component, refactor to a function component with hooks, or keep using class lifecycle methods instead of hooks.

无效尝试

常见但无效的做法:

  1. 95% 失败

    Hooks must be called synchronously during render; async callbacks break the rules of hooks.

  2. 90% 失败

    Hooks must be called unconditionally at the top level; conditional calls change the call order between renders.

  3. 80% 失败

    Multiple React copies cause the hook reference to mismatch between packages.