# 类型错误：无法读取未定义的属性（读取 'dispatch'）

- **ID:** `react/usecontext-must-be-within-provider`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

useContext 在对应的 Context Provider 外部调用，导致上下文值为 undefined。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8+ | active | — | — |
| React 17 | active | — | — |
| React 18 | active | — | — |
| React 19 | active | — | — |

## 解决方案

1. ```
   Ensure the component is rendered inside the corresponding Context Provider. For example, move the component inside the Provider tree:

// App.jsx
import { MyProvider } from './MyContext';
import ChildComponent from './ChildComponent';

function App() {
  return (
    <MyProvider>
      <ChildComponent />
    </MyProvider>
  );
}

export default App;
   ```
2. ```
   If the component must sometimes exist outside the Provider, provide a fallback default value in createContext:

const MyContext = createContext({ dispatch: () => console.warn('dispatch called outside Provider') });
   ```
3. ```
   Add a guard clause in the component to render nothing or a fallback UI when context is missing:

function ChildComponent() {
  const context = useContext(MyContext);
  if (!context) return null; // or <FallbackUI />
  const { dispatch } = context;
  // ...
}
   ```

## 无效尝试

- **** — Maskes the error but does not solve the structural issue; dispatch will be a no-op if no Provider is present, leading to silent failures. (60% 失败率)
- **** — Only works in tests or specific scenarios; in production, the real Provider is missing, so the mock may not provide the correct dispatch function. (70% 失败率)
- **** — Prevents the error but dispatch becomes undefined, causing subsequent calls to fail with 'dispatch is not a function'. (50% 失败率)
