javascript - 基于 promise 的操作成功,数据得到解决,但我收到一条错误消息

标签 javascript reactjs redux react-redux redux-thunk

所以我试图在 react 上构建这个 Action ,我需要它作为一个 promise 。 操作成功,我收到服务器的响应,但我也收到一条错误消息:

VM89852:98 Uncaught TypeError: Cannot read property 'then' of undefined.

行动:

export const fetchAllAccounts = (token, dispatch) => {
 return new Promise((resolve, reject) => {
  fetchAccountsStart((dispatch));

  return axios.get(`${API_URL}/accounts`, {
   headers: {
     'Authorization': `Bearer ${token}`,
     'Content-Type': 'application/json'
    }
   }).then(
      (response) => {
        fetchAccountsSuccess(dispatch, response.data);
        resolve(response.data);
      },(error) => {
        fetchAccountsFailed(dispatch, error.data);
        reject(error.data);
      },
   );
 });
};

这也是我如何调用此操作的方法。

 this.props.fetchAllAccounts(token)
  .then((data) => {
    console.log("#".repeat(120));
    console.log(data);
    console.log("#".repeat(120));
  }).catch((error) => {
    console.log("#".repeat(120));
    console.log(error);
    console.log("#".repeat(120));
  });

最佳答案

您的评论

heres the call from mapDispatchToProps ...
fetchAllAccounts: (token) => { fetchAllAccounts(token, dispatch) },

有你的问题,在评论里。这要么需要是

fetchAllAccounts: (token) => { return fetchAllAccounts(token, dispatch) },

fetchAllAccounts: (token) => fetchAllAccounts(token, dispatch),

了解,对于箭头函数,如果使用{},则需要返回,没有隐含的返回

作为奖励 - 删除 promise 构造函数反模式

export const fetchAllAccounts = (token, dispatch) => {
    fetchAccountsStart((dispatch));
    return axios.get(`${API_URL}/accounts`, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    }).then(
        (response) => {
            fetchAccountsSuccess(dispatch, response.data);
            return response.data;
        }, (error) => {
            fetchAccountsFailed(dispatch, error.data);
            throw error.data;
            // Borrowed from @T.J.Crowder's pastebin :p
            // Note that it's best to reject or throw an Error instance,
            // not other types; e.g., `throw new Error(error.data)` or
            // `return Promise.reject(new Error(error.data))`

        },
    );
};

关于javascript - 基于 promise 的操作成功,数据得到解决,但我收到一条错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45754429/

相关文章:

javascript - 为什么removeClass不能正常工作?

javascript - 如何使 <div> 标签内的元素一次消失一个

google-maps - React-google-maps +redux - 获取新位置时如何将 map 居中?

javascript - 为什么 .then() 没有返回 JavaScript 获取所需的值?

redux - 如何让下拉菜单在 Statelesswidget 上工作

JavaScript:递归函数无法正常工作

javascript - jquery中的淡入淡出效果

javascript - ReactJS中的通用按钮组件

reactjs - 使用 Redux 时如何使组件可重用

redux - 如何为 combineReducers 提供正确的状态切片