React 16 中的错误边界(Error Boundaries)与全局错误处理

目录
[隐藏]

自 React 16 起,任何未被错误边界捕获的错误将会导致整个 React 组件树被卸载。

对于开发已久且 Code Review 不是那么严格的庞大项目来说,在升级到 React 16 以后,可能会发现以前只偶尔在局部出现影响不大而未获得足够关注的异常,现在会时常导致整个应用垮掉。

React 16 引入了错误边界(Error Boundaries)来解决这种情况。

1 错误边界(Error Boundaries)基本用法

如果一个类组件定义了下面生命周期方法中的任何一个或全部,则这个类组件将成为一个错误边界:

  • static getDerivedStateFromError(error)

在 render 阶段当子组件抛出错误后调用该静态方法,接收的参数 err 是子组件抛出的错误。方法返回值作为组件更新后的 state,以供 render 方法渲染备用 UI。示例:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return <h1>出错了!</h1>;
    }
    return this.props.children;
  }
}
  • componentDidCatch(error, info)

在子组件抛出错误的时候调用,主要接收两个参数:

error:抛出的错误信息
info:带有组件错误栈的对象,包含了哪个组件引发的错误信息

该生命周期方法在 commit 阶段被调用的,因此允许进行副作用。示例:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  // static getDerivedStateFromError(error) {
  //   return { hasError: true };
  // }
  componentDidCatch(error, info) {
    this.setState({hasError: true});
    console.error(error, info.componentStack);
  }
  render() {
    if (this.state.hasError) {
      return <h1>出错了!</h1>;
    }
    return this.props.children;
  }
}

注意点:

  • 错误边界只能捕获树中子组件的错误,不能捕获组件本身的错误
  • 只能使用错误边界来捕获异常或者是从异常中恢复
  • 不能将错误边界用于控制流程

2 定义全局默认的错误边界(Error Boundaries) 处理函数

考虑到整个应用的健壮性,针对每个主要组件设计错误边界(Error Boundaries)策略在 React 16 以后是有必要的。

2.1 定义用于 Error Boundaries 处理的 HOC 组件

一种简单的方式是设计一个 HOC 组件,然后用装饰器模式应用于要包裹的业务组件:

export default tip => EBWrapComponent => {
  return class ErrorBoundary extends React.Component{
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }
    static getDerivedStateFromError(error) {
      return { hasError: true };
    }
    componentDidCatch(error, info) {
      console.error(error, info.componentStack);
    }
    render() {
        if (this.state.hasError) {
          if (!tip) return;
          return <h2>{tip}</h2>;
        }

        return <EBWrapComponent />;
    }
  }
}

应用示例:

@ErrorBoundary('i am not ok')
export default class LzwmeTestComponent extends React.Component {
  // ...
}

2.2 全局性兼容:定义默认的 componentDidCatch 方法

对于开发已久的存在数百上千个组件的庞大应用来说,给主要组件增加错误边界逻辑这个工作仍然会变得繁琐不堪,仅给主模块组件设置则会使得局部组件的异常放大到整个模块内。一种简单的处理方式可以是给 React.Component 定义默认的生命周期方法 componentDidCatch

if (!React.Component.prototype.componentDidCatch) {
    React.Component.prototype.componentDidCatch = (error, info) => {
      return Sentry.captureException(error, null, info);
    }
}

因为所有组件都是继承于 React.Component,所以所有组件都继承了默认的生命周期方法componentDidCatch,所以出现渲染异常的组件会在其父组件被拦截和处理。当然因为没有在 componentDidCatch 方法中自行更新 state 或定义 static getDerivedStateFromError 方法更新 UI,React 还是会抛出一个 Warning 警告,但至少不会导致整个应用都被卸载了。

当然,最根本的还是不应仅依赖于输入数据的常规格式,应要求组件开发尽量充分地考虑异常判断与处理,以保证组件自身的健壮性。

相关参考

  • https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
  • https://react.docschina.org/docs/error-boundaries.html
点赞 (0)

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code