node.js - Redux-Thunk "Actions must be plain objects. Use custom middleware for async actions."

标签 node.js reactjs redux react-redux redux-thunk

使用 Thunk 中间件创建我的商店

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
    reducer, 
    initialState,
    applyMiddleware(thunk)
);

并创建调用 promise 的操作

export function getArticle(url) {
  return function (dispatch) {
    fetchArticle(url).then( 
      article => dispatch(setArticle(article)),
    );
  };
}

function fetchArticle(url) {

  return new Promise((resolve, reject) => {

    request
     .get(url)
     .end( (err, res) => {
       if (err || !res.ok) {
         reject('Oh no! error');
       } else {
         resolve(res.body);
       }
     });

  }) 
}

export function setArticle(article){
  return {
    type: constants.SET_ARTICLE,
    article
  }
}

在我的文章组件中,我在 componentDidMount() 上调用调度

componentDidMount(){
  this.props.dispatch(
    getArticle('http://api.example.com/')
  );
}

但出现错误:“操作必须是普通对象。使用自定义中间件进行异步操作。”。

这个设置有什么问题吗?我尝试调用 compose(applyMiddleware(thunk)) 但无济于事。

最佳答案

您的代码看起来不错,只是缺少如何处理错误( promise 拒绝)。您的 api 可能会返回错误,而您没有处理它,这可能会导致该错误消息。

尝试添加

export function getArticle(url) {
  return function (dispatch) {
    fetchArticle(url)
      .then(article => dispatch(setArticle(article)))
      .catch(err => dispatch({ type: 'SOME_ERROR', err }));
  };
}

关于node.js - Redux-Thunk "Actions must be plain objects. Use custom middleware for async actions.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772168/

相关文章:

javascript - 在 node.js 中抓取经过身份验证的网站

javascript - 使用useReducer时如何在useCallback中获取当前状态?

reactjs - Reactstrap Fieldset 图例不是方形显示

javascript - 如何在写操作中使用firebase数据库推送方法生成的 key ?

reactjs - 如何调度等待其他异步操作完成的 redux 操作?

javascript - React redux 不同步 mapStateToProps 中的 Prop

javascript - 我可以在 ES6 的父类静态方法中使用类变量吗?

python - 在 AWS Lambda 上使用来自 Python 的 NodeJS 4 脚本

node.js - 是否有任何引擎可以直接执行 TypeScript 代码?

reactjs - 对象是 .map 中的 'unknown' 类型吗?