所以我试图在 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/