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

Redux Toolkit调用createAsyncThunk报AnyAction类型错误怎么解决?

报错原因

你的错误核心是手动清空了Redux Toolkit默认的中间件配置,丢失了处理异步action的thunk中间件和对应类型支持:

  • Redux Toolkit的configureStore默认内置了redux-thunk中间件,用来识别、执行createAsyncThunk生成的异步函数类型action
  • 你手动配置了middleware: [],直接清空了所有默认中间件,此时store的dispatch只能接收带type字段的普通同步action(也就是类型定义里的AnyAction),而fetchUser()返回的是AsyncThunkAction类型的函数,不符合普通action的类型约束,因此抛出缺少type属性的报错。
可行解决方案

方案1:删除自定义middleware配置(最推荐,无特殊需求选这个)

如果你没有自定义中间件的需求,直接删掉store.ts里的middleware: []这一行即可,默认会加载thunk等内置中间件,类型自动适配:

// 修改后的store.ts
export const store = configureStore({
    reducer: {
        auth: authReducer
    },
    // 删掉middleware: []配置项
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

方案2:基于默认中间件拼接自定义中间件

如果你确实需要添加自定义中间件,不要直接赋值空数组,用官方提供的getDefaultMiddleware方法获取默认中间件后再拼接你的自定义中间件,保留thunk能力:

// 修改后的store.ts 示例(以添加redux-logger中间件为例)
import logger from 'redux-logger'

export const store = configureStore({
    reducer: {
        auth: authReducer
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

修改完成后重新编译,原代码中dispatch(fetchUser())的报错就会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:04