【问题标题】:Possible Unhandled Promise Rejection with async / awaitasync / await 可能导致未处理的 Promise Rejection
【发布时间】:2018-09-03 07:31:59
【问题描述】:

在 ReactNative 组件中,当我按下按钮时,执行此函数时出现“可能未处理的 Promise Rejection”错误:

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

我不知道为什么,因为它在 try / catch 块中。

更新
这是错误函数:

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

【问题讨论】:

  • 那么error(error) 很可能会抛出异常,因为error 不是函数。
  • 你的 'error()' 方法在做什么?如果它抛出一个错误,那么 onAdd 也会。
  • 您的代码是否应该对responseJson 执行某些操作?喜欢退货吗?

标签: javascript react-native promise async-await


【解决方案1】:

问题是你在这里用catch 参数重新定义符号error

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

这样就隐藏了您的 error() 函数。改成这个(两个符号的名字不同):

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

因此,当您尝试调用 error(error) 时,您正在尝试执行一个抛出的非函数,这会导致 onAdd() 拒绝异步函数返回的承诺并且您没有 .catch() 处理程序在那个函数调用上(因为你认为它不会拒绝)。而且,只要您编写的 catch() 处理程序不会自行抛出,那么您的 Promise 就不会拒绝,但您的编码错误会导致它抛出。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我在onpress属性上调用函数,onPress={() => this.onAdd(item)}
    猜你喜欢
    • 2020-09-13
    • 2018-04-12
    • 2017-01-25
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    相关资源
    最近更新 更多