警告:reducerPath "api" 处的 RTK-Query API 中间件尚未添加到商店

Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store

我正在尝试向已经使用 RTK 查询的商店添加自定义中间件。 但我收到“警告:RTK 查询的中间件 API 在 reducerPath “api” 尚未添加到商店中。”运行时出错,尽管我确实添加了 api 中间件。 这是我的 store.ts 文件:

import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { apiSlice } from './apiSlice'
import { homeModeReducer, workingReducer, bannersReducer, latestEventDataReducer } from './reducers/reducers'
import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux'
import { latestMiddleware } from './middleware'

const reducer = combineReducers({
    [apiSlice.reducerPath]: apiSlice.reducer,
    mode: homeModeReducer,
    working: workingReducer,
    banners: bannersReducer,
    latestEventData: latestEventDataReducer
})

const store = configureStore({
    reducer,
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(latestMiddleware).concat(apiSlice.middleware)
})

export default store
export type RootState = ReturnType<typeof reducer>;
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

我的中间件定义为:

import { Middleware } from 'redux'
import { RootState } from './store'

export const latestMiddleware: Middleware<
    {}, // Most middleware do not modify the dispatch return value
    RootState
> = storeApi => next => action => {
    console.log(action.type)
    return storeApi.getState() // correctly typed as RootState
}

它编译正确但在运行时失败。有帮助吗?

你的 latestMiddleware 没有调用 next(action),这意味着下一个中间件(最后是 reducer)将永远不会被执行。