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

Is there a way to globally catch unhandled promise exceptions in reactjs?

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

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

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

class TopComponent extends React.Component {
 componentDidMount() {
    window.onunhandledrejection = (err) => {
      // handle error
    }
  }
}