redux Async Action Error: Actions must be plain objects. Use custom middleware for async actions

redux Async Action Error: Actions must be plain objects. Use custom middleware for async actions

我用redux thunkMiddle实现了async action,但是在action中发送Http请求的时候报错了,err是:

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'));

那么,如何解决这个问题呢?

一个 thunk 必须 return 一个函数 - 你的一些代码路径不会导致任何东西被 returned。

尝试通过将其包装在一个函数中来改变您的操作,您可以 return:

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))
        });
    }
};