简体   繁体   English

异步/等待可能导致未处理的承诺拒绝

[英]Possible Unhandled Promise Rejection with async / await

In a ReactNative component, when I press a button I got the "Possible Unhandled Promise Rejection" error when I execute this function: 在ReactNative组件中,当我按下一个按钮时,执行此函数时出现“可能的未处理的承诺拒绝”错误:

async onAdd(item) {
    try {
        const response = await fetch('url', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                event_id: item.id,
                event_type: item.event_type,
            })
        });
        const responseJson = await response.json();
    } catch (error) {
        error(error);
    }
}

I do not know why since its in a try / catch block. 我不知道为什么在try / catch块中。

UPDATED 更新
This is the error function: 这是错误函数:

function error(value) {
    if (console) {
        console.error(value)
    }
}

The problem is you are redefining the symbol error here with the catch argument: 问题是您在这里使用catch参数重新定义符号error

} catch (error) {
    error(error);
}

so that hides your error() function. 这样就隐藏了error()函数。 Change to this (with different names for the two symbols): 更改为此(两个符号使用不同的名称):

} catch (err) {
    error(err);
}

So, when you try to call error(error) you're trying to execute a non-function which throws which causes onAdd() to reject the promise that the async function returns and you don't have a .catch() handler on that function call (because you didn't think it could reject). 因此,当您尝试调用error(error)您尝试执行的非函数抛出会导致onAdd()拒绝异步函数返回的承诺,并且您没有.catch()处理函数该函数调用(因为您认为它不能拒绝)。 And, as long as your catch() handler is written so that it doesn't throw itself, then your promise won't reject, but your coding error was causing it to throw. 而且,只要编写了catch()处理函数,使其不会自身抛出,那么您的诺言就不会被拒绝,但是您的编码错误导致了它的抛出。

The async function itself also returns a Promise. async函数本身也会返回Promise。 A very effective way of what's rejecting, is to just add a .catch to the result of onAdd() . 拒绝的一种非常有效的方法是在onAdd()的结果中添加.catch The actual error should immediately pop up 实际错误应立即弹出

调用此函数的方法也应该处理错误,可能在您的React类上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM