Redux中异步action怎么处理才不会报错?

Mr.硕泽 阅读 50

我在用Redux写一个登录功能,dispatch一个异步action时老是报错,说“Actions must be plain objects”。我试过直接在action里写async函数,但好像不行。

网上说要用redux-thunk,但我配置了中间件还是有问题。我的action大概是这样:

const login = async (credentials) => {
  const response = await api.login(credentials);
  return { type: 'LOGIN_SUCCESS', payload: response.data };
};

这样写到底哪里不对?该怎么改才能正常dispatch异步操作?

我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
迷人的月怡
哈,这个报错我太熟悉了,每次看到"Actions must be plain objects"都想砸键盘。你的问题在于直接dispatch了一个async函数,Redux默认只接受普通对象action。

常见解决方案是用redux-thunk中间件处理异步action,但要注意几个关键点:

1. 首先确保正确配置了thunk中间件,代码应该是这样的:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const store = createStore(rootReducer, applyMiddleware(thunk));


2. 然后你的action creator应该返回一个函数而不是直接返回action对象,像这样改:
const login = (credentials) => async (dispatch) => {
try {
const response = await api.login(credentials);
dispatch({ type: 'LOGIN_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'LOGIN_FAILURE', error });
}
};


3. 调用的时候还是正常dispatch:
dispatch(login(username, password))

另外建议加个错误处理,不然请求失败时会很痛苦。我之前就吃过亏,调试了半天才发现是没catch错误。

如果用thunk还是有报错,检查下中间件配置顺序对不对,还有redux版本兼容性问题。现在大家都用@reduxjs/toolkit了,里面默认集成了thunk,写起来会更简单些。
点赞
2026-03-07 18:08