React 16 Error Boundary组件(使用componentDidCatch)显示未捕获的错误

时间:2017-10-19 17:12:51

标签: reactjs create-react-app

我使用create-react-app启动了一个应用,我有这个Error Boundary组件:

import React from 'react'

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

  componentDidCatch(error, info) {
    console.log('shouldnt I see this logged??')

    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

我在这个App组件中使用它:

import React from 'react'
import ErrorBoundary from './ErrorBoundary'


class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <div>
          <button onClick={() => { throw new Error('lets throw an error') }}>
            Click to throw error
          </button>
        </div>
      </ErrorBoundary>
    );
  }
}

export default App;

我期待如果我单击App中的按钮,应该捕获抛出的错误,我应该看到这是从ErrorBoundary记录的:“我不应该看到这个记录吗?”。但我没有看到记录,它打破了应用程序:

enter image description here

我误解了什么吗?

2 个答案:

答案 0 :(得分:3)

没有任何反应的原因是这是事件处理程序中的错误,并且它们不会被错误边界捕获。 error-handling blog post阐明了捕获的错误:

  

错误边界在渲染期间,生命周期方法以及它们下面的整个树的构造函数中捕获错误。

没有错误边界,捕获这些错误会非常棘手(在React 16中,即使生命周期方法错误也会使整个应用程序渲染消失。)

编辑:actual docs更清楚哪些错误被捕获。另请注意,server { ..other configs.. location /reactApp { root /var/www; index reactApp/index.html; try_files $uri $uri/ /index.html; } ..other configs.. } 使用create-react-app包,在开发服务器版本之后,会在短暂的时间后用错误屏幕替换整个呈现。为了更好地发现您的错误被捕获,您可以运行生产构建。

答案 1 :(得分:0)

错误边界不能捕获以下错误:

  1. 列表项
  2. 事件处理程序
  3. 异步代码(例如setTimeout或requestAnimationFrame回调)
  4. 服务器端渲染
  5. 错误边界本身(而不是其子级)引发的错误