react
runtime_error
ai_generated
true
类型错误:无法读取 undefined 的属性(读取 'dispatch')。此错误位于:ConsumerComponent (at App.js:10)
TypeError: Cannot read properties of undefined (reading 'dispatch'). This error is located at: in ConsumerComponent (at App.js:10)
ID: react/context-not-provided
95%修复率
88%置信度
1证据数
2023-04-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
根因分析
组件尝试使用 useContext 访问上下文值,但它没有被相应的 Provider 组件包裹,因此上下文值为 undefined。
English
A component tries to use useContext to access a context value, but it is not wrapped in the corresponding Provider component, so the context value is undefined.
官方文档
https://reactjs.org/docs/context.html解决方案
-
Wrap the component tree with the Provider: `<MyContext.Provider value={{ dispatch }}><ConsumerComponent /></MyContext.Provider>` -
If the Provider is already present but value is undefined, ensure the value prop is correctly passed: `<MyContext.Provider value={dispatch}>` (not just `value={}`)
无效尝试
常见但无效的做法:
-
Importing the context directly and trying to use it as a value
75% 失败
The context object itself is not the value; it must be provided via a Provider.
-
Adding a default value to createContext but not wrapping in Provider
50% 失败
The default value is only used when there is no Provider at all, but if the component is wrapped in a Provider without a value prop, the context is still undefined.
-
Using useContext inside a class component
65% 失败
useContext is a hook and cannot be used in class components; use Context.Consumer instead.