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

使用React Redux时遇Actions必须为纯对象错误,求解决方案

解决Redux错误:Actions must be plain objects. Use custom middleware for async actions

问题原因分析

你遇到的错误有两个核心原因:

  1. 错误地将普通函数作为action传入dispatch:在useEffect中你调用了dispatch(getUserArticle()),但getUserArticle是自定义普通函数,并非Redux action对象或action creator,dispatch无法直接处理这类函数。
  2. Store配置覆盖了默认中间件:使用configureStore时直接指定middleware: [thunk]会替换掉Redux Toolkit默认提供的所有中间件(包括序列化检查等),虽然thunk是异步action所需,但这种写法会丢失默认中间件,引发潜在问题。

具体修正步骤

1. 修正useEffect中的函数调用

将useEffect里的dispatch(getUserArticle())改为直接调用getUserArticle()——因为getUserArticle内部已经执行了dispatch操作:

useEffect(()=>{
    getUserArticle()
}, [user._id]) // 添加user._id作为依赖项,确保user ID变化时重新触发请求

同时修正getUserArticle函数里的setArticle调用(原写法参数错误):

const getUserArticle =() =>{
    dispatch(fetchUserArticle(user._id))
        .unwrap()
        .then((res) =>{
            setArticle(res.data) // 直接设置新的文章数据,或根据需求合并旧数据
        })
}

2. 修正Store配置

Redux Toolkit的configureStore默认已经包含thunk中间件,无需手动指定。如果需要自定义中间件,应该基于默认中间件扩展而非替换:

import { configureStore } from '@reduxjs/toolkit';

const reducer = {
    auth: authReducer,
    msg: msgReducer,
    data: dataReducer
}

const store = configureStore({
    reducer: reducer,
    devTools: true,
    // 如需添加额外中间件,使用以下方式扩展默认中间件
    // middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(yourCustomMiddleware)
})

额外注意事项

  • 确保fetchUserArticle是从slice文件正确导入的action creator(createAsyncThunk返回的是可被dispatch的函数)。
  • 检查setMessage是否是有效的Redux action creator,确保它返回的是plain object类型的action。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:25:23