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

如何解决Redux中TypeError: Cannot read properties of undefined (reading 'type')错误?

解决Redux Dispatch时的TypeError: Cannot read properties of undefined (reading 'type')错误

问题原因

你遇到的错误核心是:在Metrics组件中调用了allRetail(data)这个action创建函数,但没有从对应的retailSlice文件中导入它。此时allRetail是undefined,当你执行dispatch(allRetail(data))时,相当于给dispatch传入了undefined,Redux无法识别这个无效的action,因此抛出该报错。

修复步骤

只需在Metrics组件中添加对allRetail的导入即可:

修改后的Metrics组件代码:

import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
// 新增导入语句,路径需根据你的项目结构调整
import { allRetail } from "./retailSlice";

export default function Metrics() {
  const [store, setStore] = useState();
  const dispatch = useDispatch();

  useEffect(() => {
    const baseUrl = "/api/stores";
    fetch(baseUrl)
      .then((res) => res.json())
      .then((data) => {
        dispatch(allRetail(data)); // 现在可正常分发action
        return data;
      });
  }, []);

  return (
    <div>
      ...
    </div>
  );
}

额外验证点

  • 确认retailSlice已正确注册到Redux Store中(若未注册,需在Store配置文件中添加):
import { configureStore } from "@reduxjs/toolkit";
import allRetailReducer from "./retailSlice";

export const store = configureStore({
  reducer: {
    retailList: allRetailReducer, // 对应slice的name字段
  },
});
  • 确保API返回的data是预期的数组类型,避免后续state更新异常。

内容的提问来源于stack exchange,提问作者Ptrades

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:31:15