【问题标题】:redux Async Action Error: Actions must be plain objects. Use custom middleware for async actionsredux 异步操作错误:操作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2018-01-30 15:10:08
【问题描述】:

我使用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)

有我的代码:

在我的操作中,我使用超级代理发送请求,我的代码如下:

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

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

【问题讨论】:

    标签: asynchronous redux redux-thunk


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2019-12-26
      • 2021-11-04
      • 2020-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多