Redux RTK Query报错getDefaultMiddleware is not a function求助
问题根因
你的代码存在配置层级错误:middleware 是 configureStore 顶层的配置属性,不应该嵌套在 reducer 对象内部。你现在把 middleware 放到了 reducer 里,所以传递给 middleware 回调的入参根本不是 RTK 提供的 getDefaultMiddleware 函数,自然会报不可调用的错误。
修复后的代码
import { Action, configureStore, ThunkAction } from '@reduxjs/toolkit'; import { setupListeners } from '@reduxjs/toolkit/query'; import { myApi } from './services/api'; import authorReducer from './slices/authorSlice'; import transcriptReducer from './slices/transcriptSlice'; export const store = configureStore({ reducer: { [myApi.reducerPath]: myApi.reducer, author: authorReducer, transcript: transcriptReducer, }, // middleware与reducer平级,不要放在reducer内部 middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(myApi.middleware), }); setupListeners(store.dispatch); // Infer the `RootState` and `AppDispatch` types from the store itself export type RootState = ReturnType<typeof store.getState>; export type AppDispatch = typeof store.dispatch; export type AppThunk<ReturnType = void> = ThunkAction< ReturnType, RootState, unknown, Action<string> >;
附加排查项
- 确认你的
@reduxjs/toolkit依赖安装正确,没有版本冲突,可以删除 node_modules 和 lock 文件后重新执行npm install或yarn install修复 - 如果是 TypeScript 项目,确认你的 TS 版本不低于 4.2,符合 RTK 1.6.1 对 TypeScript 版本的要求
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

