基于承诺的操作成功,数据已解析,但我收到错误消息



所以我正在尝试在反应上构建此操作,我需要它作为承诺。 操作成功,我收到来自服务器的响应,但我也收到一条错误消息:

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

您的评论

这是来自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))`
},
);
};

最新更新