首页 > 解决方案 > 我收到此错误:操作必须是普通对象。使用自定义中间件进行异步操作

问题描述

我收到错误:

 Actions must be plain objects. Use custom middleware for async actions.

我已经尝试了以下 Stack Overflow 问题中的解决方案,但没有奏效:
React-Redux: Actions must be plain objects。使用自定义中间件进行异步操作

行动

export async function signupp(data){
    console.log('In signupp:');
    try{
        const request = await axios({
            method:'POST',
            url:'http://192.168.1.10:3003/users/signup',
            data:{
                email:data.email,
                password:data.password
            },
        }).then(response=>{
            console.log(response.data);
            return response.data
        }).catch( e => {
            console.log(e);
            return false
        }); 
        return {
            type:'signup',
            payload:request
        }
    }
    catch(e) {
        console.log(e);
        return false;  
    } 
}

减速器

export default function(state={},action){
    switch(action.type){
        case 'signup':
            return {
                ...state,
                auth:{
                    email: action.payload.email,
                    password:action.payload.password
                }
            }    
    }
}

店铺

const createStoreWithMiddleware = applyMiddleware()(createStore);
const appRedux = () => (
    <Provider store = {createStoreWithMiddleware(reducers)}>
        <App/>
    </Provider>
)
AppRegistry.registerComponent(appName, () => appRedux);

顺便说一句,我在日志中得到了正确的响应。

标签: react-nativereduxreact-redux

解决方案


在组件内部,在您调用signupp函数的地方,您有mapDispatchToProps函数作为 react-redux lib 的 connect 函数中的回调,它在幕后执行诸如dispatch(signupp()) 之类的操作(或者您可能正在执行 dispatch直接没有 react-redux lib)。根据 redux API,这个 dispatch 函数期望接收一个普通对象,但是你的 signupp() 函数返回一个 promise(因为你有 async 里面)。

要解决这个问题,你可以简单地使用redux-thunk中间件。您还可以在 redux 文档部分中看到一些关于异步操作的示例。

另一种解决方案可能是将获取逻辑移动到组件,然后仅发送带有从请求中收到的数据的普通对象。


推荐阅读