Skip to content

错误边界

一句话解释

错误边界是 类组件那个 catches JavaScript 错误 anywhere in 它的 child 组件树 and displays fallback UI.

用大白话说

Error boundaries are React components that catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. When an error is caught, the boundary shows a fallback UI instead of the crashed component, and the rest of the app keeps working.

Error boundaries are currently class components only — they implement 静态 getDerivedStateFromError(错误) (to update state) and/or componentDidCatch(错误, 信息) (to log the error). You wrap any subtree with an error boundary to isolate failures.

Note: error boundaries do not catch errors in event handlers, async code, or setTimeout callbacks — those need try/catch. They catch only rendering errors.

示例

jsx
class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

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

如果任何 child throws 期间渲染, getDerivedStateFromError 设置 hasError 到真, and 边界 shows fallback 消息.

相关术语

相关资源

相关课程

  • 错误边界

    学习错误边界 for graceful 错误 handling.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表