# 错误: 无效的钩子调用。钩子只能在函数组件的主体内部调用。可能的原因：1. React 和渲染器（如 React DOM）版本不匹配；2. 违反了钩子规则；3. 同一个应用中有多个 React 副本。

- **ID:** `react/error-invalid-call-of-useeffect-in-callback`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

钩子（例如 useEffect、useState）在普通 JavaScript 函数、回调或类组件中被调用，违反了钩子规则，要求钩子必须在 React 函数组件的顶层调用。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 18.2.0 | active | — | — |
| React 17.0.2 | active | — | — |
| React 16.14.0 | active | — | — |

## 解决方案

1. ```
   Ensure all hook calls are at the top level of a function component, never inside loops, conditions, or nested functions. Example: function MyComponent() { useEffect(() => { /* ... */ }, []); return <div />; }
   ```
2. ```
   Check for duplicate React instances in your bundle by running `npm ls react` and ensure only one version exists. If using webpack, add `resolve: { alias: { react: require.resolve('react') } }` to webpack config.
   ```
3. ```
   Convert class components to function components if you need to use hooks. Example: class MyComp extends Component { render() { return <div />; } } becomes function MyComp() { return <div />; }
   ```

## 无效尝试

- **Move the hook call to the top of a class component's render method** — Hooks are not supported in class components; they must be used in function components. (100% 失败率)
- **Wrap the hook call in a try-catch block** — The error is thrown as an invariant, not a catchable exception, and try-catch doesn't prevent the violation. (95% 失败率)
- **Use React.forwardRef to pass hooks to child components** — forwardRef doesn't change where hooks can be called; hooks still must be in the component body. (90% 失败率)
