我使用redux thunkMiddle来实现异步操作,但是当我在动作中发送Http请求时出错,错误是:
VM711:3 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
at Object.performAction (<anonymous>:3:2312)
at liftAction (<anonymous>:2:27846)
at dispatch (<anonymous>:2:31884)
at Object.dispatch (bundle.js:22661)
at dispatch (<anonymous>:2:1620)
at Object.submitForm (bundle.js:23120)
at Form.submitForm (bundle.js:23168)
at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4532)
at executeDispatch (bundle.js:4332)
at Object.executeDispatchesInOrder (bundle.js:4355)
有我的代码:
在我的行动中,我使用superagent发送请求,我的代码如下:
import superagent from 'superagent'
import async from 'async'
export const onSubmitForm = userInfo => {
async.waterfall([
(done) => {
superagent
.post('/userInfo')
.send(userInfo)
.end((err, res) => {
done(err, res.body)
});
}
], (err, data) => {
return (dispatch) => (dispatch(submitFormAction(data)))
});
};
export const submitFormAction = data => {
return {
type: "USER_INFO",
data
}
};
这是我的输入文件,我从redux导入thunkMiddle:
import React from 'react';
import {render} from 'react-dom';
import {createStore, applyMiddleware} from "redux";
import { composeWithDevTools } from 'redux-devtools-extension';
import {Provider} from "react-redux";
import reducer from './reducers/index';
import thunkMiddleware from 'redux-thunk';
import {App} from './containers/App';
const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunkMiddleware)));
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
那么,如何解决这个问题?
答案 0 :(得分:0)
thunk必须返回一个函数 - 你的一些代码路径不会返回任何内容。
尝试通过将其包装在可以返回的函数中来改变您的操作:
export const onSubmitForm = userInfo => {
return function(dispatch) {
async.waterfall([
(done) => {
superagent
.post('/userInfo')
.send(userInfo)
.end((err, res) => {
done(err, res.body)
});
}
], (err, data) => {
dispatch(submitFormAction(data))
});
}
};