有没有办法全局捕获 reactjs 中未处理的承诺异常?

use*_*767 1 javascript exception-handling promise reactjs react-redux

我尝试使用 componentDidCatch,但看起来该钩子仅用于渲染组件中的实际错误。Promises 可以在组件层次结构之一中发生,但实际上直到稍后才会抛出。

我还在我的函数周围包裹了一个 tryCatch,它执行应用程序的初始渲染,但也未能捕获异常。(出于我认为的原因)

小智 5

您可以将onunhandledrejection事件附加到最顶层的组件 componentDidDount 方法。

class TopComponent extends React.Component {
 componentDidMount() {
    window.onunhandledrejection = (err) => {
      // handle error
    }
  }
}
Run Code Online (Sandbox Code Playgroud)