我有以下代码:
export function fetchValueFromApi(){
return function act(dispatch){
dispatch(fetchingLimit);
return fetch('https://someapi/v1/foo/bar?api_key=123456789')
.then(response =>{
console.log("response",response.json());
response.json();
}).then(json =>{
if (json.data()) {
dispatch(receivingValue(json.data.result))
} else {
throw new Error('Error');
}
}).catch(error => dispatch(receivingValueFailed(error)))
}
}
现在我知道这个电话不会成功。我期待它失败并进入捕获。但是,我收到此错误:
可能未处理的承诺拒绝
所以出于某种原因,我们没有击中.catch
。
我该怎么解决这个问题?
所以你正在抓住这个问题,而不是你预期的错误。
就提取而言,403不是错误,因为请求本身已成功(响应不是您的应用程序所期望的)。你必须自己处理40X错误。正如您的console.log所揭示的那样,异常发生在您到达throw new Error
之前。
当遇到网络错误或服务器端的CORS配置错误时,fetch()promise将拒绝TypeError,尽管这通常意味着权限问题或类似问题 - 例如,404不构成网络错误。
来自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
你应该
response.json()
:.then(response => response.ok && response.json())
if (json && json.data)
你不是return
ing你的then
处理程序的承诺,所以没有链接。甚至还没有等待回复机构。 catch
处理程序没有链接到实际拒绝的承诺,因此错误确实未处理。
export function fetchValueFromApi(){
return function act(dispatch){
dispatch(fetchingLimit);
return fetch('https://someapi/v1/foo/bar?api_key=123456789')
.then(response => {
var body = response.json();
console.log("response body", body);
return body;
// ^^^^^^
}).then(json => {
if (json.data ) {
// ^
return dispatch(receivingValue(json.data.result))
// ^^^^^^
} else {
throw new Error('Error');
}
}).catch(error =>
dispatch(receivingValueFailed(error))
)
}
}
请记住,箭头函数仅在使用简洁的正文语法时隐式返回表达式值,即没有块括号。