You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用useReducer+Context报错:dispatch is not a function,求排查

问题原因与修复方案

错误的核心在于UseCountActions函数的实现:它直接返回了CounterContextDispather这个Context对象,而非通过useContext获取该Context中提供的dispatch函数。这导致你在组件中拿到的dispatch并不是实际的调度函数,而是Context本身,自然会抛出dispatch is not a function的错误。

修复代码

修改CounterProvider.js中的UseCountActions函数:

export const UseCountActions = () => {
  // 调用useContext获取Context中的dispatch值,而非直接返回Context对象
  return useContext(CounterContextDispather);
};

额外验证项

确保CounterOne组件被CounterProvider包裹在组件树中,比如在根组件中这样使用:

import CounterProvider from './CounterProvider';
import CounterOne from './CounterOne';

function App() {
  return (
    <CounterProvider>
      <CounterOne />
    </CounterProvider>
  );
}

修改完成后,点击按钮即可正常调用dispatch函数,计数器的加、减、重置功能就能正常运行。

内容的提问来源于stack exchange,提问作者sajad saeedi azad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:57:23