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

React 16 Error Boundary component (using componentDidCatch) shows uncaught error

我使用 create-react-app, and I have this 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 中记录的错误:"shouldnt I see this logged??"。但我没有看到记录,它破坏了应用程序:

我是不是误会了什么?

之所以没有任何反应,是因为这是事件处理程序中的一个错误,并且这些错误边界没有捕获到。 error-handling blog post 阐明捕获了哪些错误:

Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

如果没有错误边界,这些错误将非常难以捕捉(在 React 16 中,即使是生命周期方法错误也会使您的整个应用程序渲染消失。)

编辑:actual docs 更清楚捕获了哪些错误。另请注意 create-react-app 使用 react-error-overlay 包,它在开发服务器构建中会在片刻后用错误屏幕替换整个渲染。为了更好地发现您的错误,您可以 运行 生产版本。

错误边界不捕获错误:

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