我正在使用react-redux和redux-thunk实现异步动作创建者。但是,我收到以下错误消息:未捕获的错误:操作必须是普通对象。使用自定义中间件进行异步操作。

我知道动作应该是简单的对象,而像thunk这样的中间件应该负责处理不是它们的情况。我已经阅读了几本教程,并研究了在此上可以找到的每个SO问题,但是我仍然无法弄清楚哪里出了问题。我是错误地设置了thunk,还是我以不好的方式使用动作创建者?这可能是webpack或其他错误吗?

在下面,我包括了我认为相关的代码片段。请让我知道是否需要其他信息。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import rootReducer   from './reducers';
import Layout    from './components/Layout.js';
import OrderPage from './containers/order-page';


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

ReactDOM.render(
    <Provider store={store}>
        <App>
            <Route  exact path="/" component={Layout}/>
        </App>
    </Provider>,
    document.querySelector('.app'));


reducers / order.js

import { FETCH_ERR, FETCH_SUCCESS, START_FETCH } from '../actions/types';

const initialState = {
  fetching: false
};

export default (state=initialState, action)=>{
  switch (action.type) {
    case START_FETCH:
      return {
        fetching: true
      }
    case FETCH_ERR:
      return {
        err: action.payload.err,
        fetching: false
      }
    case FETCH_SUCCESS:
      return {
        price: action.payload,
        fetching: false
      }
    default:
        return state
  }

}


动作/price-fetch.js

import axios from 'axios'

const FETCH_ERR = 'FETCH_ERR'
const FETCH_SUCCESS = 'FETCH_SUCCESS'
const START_FETCH  = 'START_FETCH'


const fetchSucc = (data)=>{
  return{
    type:FETCH_SUCCESS,
    payload:data
  }
}

const fetchFail = (message)=>{
  return{
    type:FETCH_ERR,
    payload:message
  }
}

const startFetch = () =>{
  return{
    type: START_FETCH,
    payload:null
  }
}

const fetchPrices = () =>{
  return async (dispatch) =>{
    try {
      dispatch(startFetch())
      let data = await axios.get('mybackendurl')
      dispatch(fetchSucc(data))
    } catch (error) {
      dispatch(fetchFail({err:'failed to get shit'}))
    }
  }
}

export {
    FETCH_ERR,
    FETCH_SUCCESS,
    fetchPrices,
    START_FETCH
}


相关的容器/order.js

import React, { Component }     from 'react';

import { connect }                      from 'react-redux';

import { fetchPrices }          from '../actions/price-fetch';

class Order extends Component {


...



  render() {
    this.props.fetchPrices();
    return ...

  }


const mapDispatchToProps = dispatch => {
  return {
    fetchPrice: () => {
      dispatch(fetchPrices())
    }
  }
}

function mapStateToProps(state){
    return {
        prices: state.order
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Order);


在此先感谢您的帮助!

最佳答案

如果有人遇到相同的问题。问题不在于上面显示的代码中,也不在于我如何调度动作。我在另一个文件中有一个关于redux-store的重复定义,这用中间件覆盖了该定义。

关于javascript - 使用redux-thunk时 Action 必须是普通对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48510067/

10-10 00:05