react
runtime_error
ai_generated
true
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%Fix Rate
88%Confidence
1Evidence
2023-04-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| [email protected] | active | — | — | — |
| [email protected] | active | — | — | — |
Root Cause
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.
generic中文
组件尝试使用 useContext 访问上下文值,但它没有被相应的 Provider 组件包裹,因此上下文值为 undefined。
Official Documentation
https://reactjs.org/docs/context.htmlWorkarounds
-
95% success Wrap the component tree with the Provider: `<MyContext.Provider value={{ dispatch }}><ConsumerComponent /></MyContext.Provider>`
Wrap the component tree with the Provider: `<MyContext.Provider value={{ dispatch }}><ConsumerComponent /></MyContext.Provider>` -
90% success If the Provider is already present but value is undefined, ensure the value prop is correctly passed: `<MyContext.Provider value={dispatch}>` (not just `value={}`)
If the Provider is already present but value is undefined, ensure the value prop is correctly passed: `<MyContext.Provider value={dispatch}>` (not just `value={}`)
中文步骤
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={}`)
Dead Ends
Common approaches that don't work:
-
Importing the context directly and trying to use it as a value
75% fail
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% fail
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% fail
useContext is a hook and cannot be used in class components; use Context.Consumer instead.