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

Redux Toolkit中ExtraReducers不生效问题求助

Redux Toolkit异步Thunk未触发extraReducers问题

我用Redux Toolkit搭建了Redux Store,调用getCompanyInfo异步Thunk时,API请求成功并返回数据,但userCompanySlice里的extraReducers对应的pending、fulfilled、rejected均未触发,导致companyInfo状态无法更新。此前其他项目用相同写法可正常运行,现寻求解决方法。

相关代码

index.ts

const createStore = () =>
  configureStore({
    reducer: rootReducer,
    devTools: false,
    middleware: getDefaultMiddleware => {
      const middleware = getDefaultMiddleware({
        immutableCheck: false,
        serializableCheck: false,
      });
      if (process.env.NODE_ENV !== "production") {
        middleware.push(logger);
      }
      return middleware;
    },
  });

export const store = createStore();
export const persistor = persistStore(store);

rootReducer.ts

import { combineReducers, Reducer, AnyAction } from "@reduxjs/toolkit";
import storage from "redux-persist/lib/storage";
import { persistReducer } from "redux-persist";
import userCompnaySlice from "./slices/userCompnaySlice";

const userCompanyDataPersistConfig = {
  key: "userCompanyData",
  storage,
};

const appReducer = combineReducers({
  userCompany: persistReducer(userCompanyDataPersistConfig, userCompnaySlice.reducer),
});

export type RootState = ReturnType<typeof appReducer>;

const rootReducer: Reducer = (state: RootState, action: AnyAction) =>
  appReducer(state, action);

export default rootReducer;

userCompanySlice.ts

import { createSlice } from "@reduxjs/toolkit";
import { userCompanyReducer } from "../../utils/types/reducerStateTypes";
import { getCompanyInfo } from "../thunks/userCompanyThunk";

const initialState: userCompanyReducer = {
  userInfo: {},
  companyInfo: {},
};

const userCompanySlice = createSlice({
  name: "userCompany",
  initialState,
  reducers: {
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
    },
    setCompanyInfo: (state, action) => {
      state.companyInfo = action.payload;
    },
  },
  extraReducers: {
    [getCompanyInfo.pending.type]: (state, action) => {
        console.log("pending");
    },
    [getCompanyInfo.fulfilled.type]: (state, action) => {
        console.log("fulfilled");
      state.companyInfo = action.payload;
    },
    [getCompanyInfo.rejected.type]: (state, action) => {
        console.log("rejected");
    },
  },
});

export const { setUserInfo, setCompanyInfo } = userCompanySlice.actions;

export default userCompanySlice;

userCompanyThunk.ts

import { createAsyncThunk } from "@reduxjs/toolkit";
import axiosApiInstance from "../../services/axios";
import { companyAPI } from "../../shared/api/apiRoutes";

export const getCompanyInfo = createAsyncThunk(
  "userCompany/getCompanyInfo",
  async () => {
    try {
      const response = await axiosApiInstance.get(companyAPI);
      console.log(response.data["data"]);
      console.log("Action type:", getCompanyInfo.fulfilled.type);
      return response.data["data"];
    } catch (e: any) {
    //   if (e.response.status >= 400 && e.response.status < 599) {
    //     throw new Error(e.response.data.message);
    //   }
    console.log(e);
    }
  }
);

调用代码

useEffect(() => {
  console.log("get company");
  dispatch(getCompanyInfo());
  getCompany();
}, [dispatch]);

解决方法

1. 改用builder回调定义extraReducers

Redux Toolkit官方推荐使用builder回调方式定义extraReducers,对象字面量写法可能因action type匹配问题失效。修改userCompanySlice.ts中的extraReducers:

extraReducers: (builder) => {
  builder
    .addCase(getCompanyInfo.pending, (state) => {
      console.log("pending");
    })
    .addCase(getCompanyInfo.fulfilled, (state, action) => {
      console.log("fulfilled");
      state.companyInfo = action.payload;
    })
    .addCase(getCompanyInfo.rejected, (state) => {
      console.log("rejected");
    });
}

2. 修复Thunk错误处理逻辑

当前Thunk的catch块未抛出错误,导致请求失败时无法触发rejected状态。修改userCompanyThunk.ts:

catch (e: any) {
  if (e.response.status >= 400 && e.response.status < 599) {
    throw new Error(e.response.data.message);
  }
  console.log(e);
  // 确保错误被抛出,触发rejected action
  throw e;
}

3. 排查redux-persist干扰

暂时移除persistReducer,直接使用原始reducer测试:

// rootReducer.ts
const appReducer = combineReducers({
  userCompany: userCompnaySlice.reducer,
});

若测试正常,再调整persist配置,添加whitelist/blacklist确保action正常传递。

4. 检查文件导入拼写

注意到文件名是userCompnaySlice(拼写为Compnay),确认所有导入路径的拼写一致,避免因拼写错误导致reducer未正确注册。

5. 启用Redux DevTools调试

将devTools设为true,通过浏览器Redux DevTools查看是否有getCompanyInfo/pending等action被分发,确认reducer是否响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:07:22