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

Redux中configureStore自定义中间件失效及createAsyncThunk疑问

关于Redux自定义日志中间件与configureStore的问题

我在Redux中配置的自定义日志中间件无法正常工作,查阅的文档和文章大多使用createStore而非configureStore,怀疑这是问题原因——目前dispatch任何函数都不会输出日志。

第一种尝试的代码

function logger({ getState }) {
  return (next) => (action) => {
    console.log("will dispatch", action);

    const returnValue = next(action);

    console.log("state after dispatch", getState());

    return returnValue;
  };
}

export const store = configureStore(
  {
    reducer: {
      auth: authReducer,
      orders: ordersReducer,
      dashboard: dashboardReducer,
      portfolio: portfolioReducer,
    },
  },
  applyMiddleware(logger)
);

第二种尝试的代码

export const logger = (store) => (next) => (action) => {
  console.log("hello from middleware");
  return next(action);
};

export const store = configureStore(
  {
    reducer: {
      auth: authReducer,
      orders: ordersReducer,
      dashboard: dashboardReducer,
      portfolio: portfolioReducer,
    },
  },
  applyMiddleware(logger)
);

异步Action示例(使用createAsyncThunk)

export const getCurrentHoldings = createAsyncThunk(
  "/portfolio/getCurrentHoldings",
  async (value, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      const userID = thunkAPI.getState().auth.user._id;
      const newObj = {
        token: token,
        userID: userID,
      };
      let url = `http://localhost:3001/api/portfolio/getCurrentHoldings`;
      const response = await axios.post(url, newObj);
      console.log("New request ran in getCurrentHoldings");
      return response.data;
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

额外疑问

之前我以为使用createAsyncThunk需要配置redux-thunk中间件,但移除thunk后代码仍能正常运行,想确认该现象的原因。

原配置代码

export const store = configureStore(
  {
    reducer: {
      auth: authReducer,
      orders: ordersReducer,
      dashboard: dashboardReducer,
      portfolio: portfolioReducer,
    },
  },
  applyMiddleware(thunk)
);

问题解答

1. 自定义日志中间件不工作的原因与解决方法

你当前的代码错误在于**configureStore的参数格式使用错误**。Redux Toolkit的configureStore和传统的createStore参数结构完全不同:

  • createStore允许将applyMiddleware返回的enhancer作为第二个参数
  • 但configureStore只接收一个配置对象,中间件必须通过对象内的middleware属性来配置

你把applyMiddleware(logger)作为第二个参数传入,不符合configureStore的API规范,导致中间件根本没被正确注册。

正确的配置方式是利用getDefaultMiddleware来添加自定义中间件(它会保留Redux Toolkit默认集成的中间件,比如thunk、不可变检查等):

function logger({ getState }) {
  return (next) => (action) => {
    console.log("will dispatch", action);
    const returnValue = next(action);
    console.log("state after dispatch", getState());
    return returnValue;
  };
}

export const store = configureStore({
  reducer: {
    auth: authReducer,
    orders: ordersReducer,
    dashboard: dashboardReducer,
    portfolio: portfolioReducer,
  },
  // 通过getDefaultMiddleware获取默认中间件数组,再追加自定义日志中间件
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger)
});

如果确实需要完全替换默认中间件(不推荐,除非你明确不需要默认功能),可以直接传入中间件数组:

middleware: [logger]

2. 移除thunk后代码仍正常工作的原因

Redux Toolkit的configureStore默认已经集成了redux-thunk中间件,这是它的标准默认配置之一。你之前手动添加thunk属于重复配置,移除后默认的thunk依然存在,因此依赖thunk的createAsyncThunk自然能正常运行。

如果需要禁用默认的thunk,可以在getDefaultMiddleware中配置:

middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: false }).concat(logger)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:35:21