Babel.js 为什么unhandlerejection事件无法捕获React中的某些错误?

anauzrmj  于 2022-12-08  发布在  Babel
关注(0)|答案(2)|浏览(218)

unhandledrejection无法在使用creat-react-app生成项目时捕获某些错误。
Example

window.addEventListener("unhandledrejection", function(e) {
  console.log(e);
  alert(e.reason);
});

function onclick() {
  Promise.resolve().then(() => {
    abcd(); // not alert
    // throw "abcd"; // alert
  });
}

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={onclick}>error</button>
    </div>
  );
}
g0czyy6m

g0czyy6m1#

虽然unhandledrejection可用于捕获未处理的承诺拒绝,但您可以使用全局错误处理程序来捕获未处理的错误

window.addEventListener('error', (errorEvent) => { 
  // handle errorEvent.error here
});
hwamh0ep

hwamh0ep2#

你可以抓住被拒绝的承诺。

someFunctionReturnsPromise()
.then(resolvedValue => { /* do stuff */ })
.then(anotherResolvedValue => { /* do more stuff */ })
.catch(error => { /* handle any rejected promises here */ })
.finally(() => { /* you can do stuff here regardless of promise resolution */ });

Handled Promise Exception
尽管如此,我现在意识到你在问为什么为unhandledrejection添加一个侦听器通常不能捕获错误。它实际上确实起作用了,并且捕获了abcd()抛出的未定义函数错误。
Unhandled event handler responding to promise rejection
值得注意的是,事件unhandledrejection没有通用浏览器支持,事实上,它在Chrome 49+中受支持。
值得注意的是,事件unhandledrejection现在在Chrome 49+、Edge 79+、Firefox 69+、Safari 11+中具有相当普遍的浏览器支持。

相关问题