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

Redux TypeScript创建Store时中间件报错问题求助

问题分析与解决

你的代码中middleware部分报错,核心原因是Redux Toolkit的getDefaultMiddleware返回的是MiddlewareArray类型,而非普通数组。直接将其展开到新数组中,会导致TypeScript无法正确推断类型,引发类型不匹配错误。

修正方案

推荐使用MiddlewareArray自带的concat方法添加自定义中间件,这种写法类型安全且符合RTK设计规范:

import { configureStore } from "@reduxjs/toolkit";
import { userAPI } from "./api/userAPI";

export const server = import.meta.env.VITE_SERVER;

export const store = configureStore({
    reducer: {
        [userAPI.reducerPath]: userAPI.reducer,
    },
    middleware: (getDefaultMiddleware) => 
        getDefaultMiddleware().concat(userAPI.middleware)
});

如果一定要用数组展开的方式,可以通过MiddlewareArray.from将普通数组转换为符合要求的类型:

import { configureStore, MiddlewareArray } from "@reduxjs/toolkit";
import { userAPI } from "./api/userAPI";

export const server = import.meta.env.VITE_SERVER;

export const store = configureStore({
    reducer: {
        [userAPI.reducerPath]: userAPI.reducer,
    },
    middleware: (getDefaultMiddleware) => 
        MiddlewareArray.from([...getDefaultMiddleware(), userAPI.middleware])
});

额外检查点

确保userAPI是通过RTK Query的createApi正确生成的——只有这样,userAPI.middleware才会是符合Redux中间件规范的类型,避免因API定义错误导致的类型问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:14:58