有可能在反应时捕获全局错误

Edg*_*rka 5 reactjs

我尝试通过https://reactjs.org/docs/error-boundaries.html实现错误边界,但它只捕获渲染错误。

react是否可以在异步进程和处理程序上实现全局 try/catch 和捕获错误之类的东西?

就像是:

try {
    ReactDOM.render(<App />, document.getElementById("root"));
} catch (error) {
    console.log("CAUGHT AN ERROR!!!!!!!")
    console.log(error);
    ReactDOM.render(<ErrorComponent />, document.getElementById("root"));

}
Run Code Online (Sandbox Code Playgroud)

Shu*_*rma 7

React 16 有一个新功能,称为错误边界。这个你可以多搜索一下。您的问题是通过这样的错误边界解决的:例如:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样包装你的应用程序组件。它将捕获所有错误:

<ErrorBoundary>
  <App />
</ErrorBoundary>
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读更多相关内容。https://reactjs.org/docs/error-boundaries.html

  • 值得引用[文档](https://reactjs.org/docs/error-boundaries.html):“错误边界**不**捕获以下错误:事件处理程序(了解更多)[和]异步代码(例如 setTimeout 或 requestAnimationFrame 回调)”。 (2认同)