componentDidMount 生命周期方法中子组件抛出的错误未在错误边界中捕获

2024-03-05

我正在学习 React,当 API 服务器不可用时,无法获取错误边界来捕获子组件中 axios http 请求引发的网络连接错误。

我可以看到错误记录在子组件的 catch 处理程序中,但是 ErrorBoundary 组件没有捕获 throw 语句。

任何想法如何让错误边界捕获抛出的错误组件已挂载生命周期方法?

父级 - App.tsx

export class App extends React.Component<AppProps, {}> {
  public render(): JSX.Element {
    return (
      <div>
        <ErrorBoundary>
          <AppBar color="primary" position="static">
            <Toolbar>
              <TypoGraphy variant="h6" color="inherit">
                Course App
              </TypoGraphy>
              <NavBar />
            </Toolbar>
          </AppBar>
          <CourseList />
        </ErrorBoundary>
      </div>
    );
  }
}

子级 - CourseList.tsx

  componentDidMount(): void {
    console.log('CourseList::componentDidMount');

    const dataSource: RestDataCourse = new RestDataCourse();
    dataSource
      .getCourses()
      .then(courseList => {
        this.setState({ courses: courseList });
      })
      .catch(error => {
        console.error(`Error retrieving courses => ${JSON.stringify(error)}`);
        throw error;
      });
  }

错误边界

import * as React from 'react';

interface ErrorBoundaryProps {
  hasError: boolean;
  error: Error;
  info: React.ErrorInfo;
}
export default class ErrorBoundary extends React.Component<
  {},
  ErrorBoundaryProps
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: undefined, info: undefined };
  }

  componentDidCatch(error: any, info: any): void {
    console.log('ErrorBoundary has encountered an error');
    this.setState({ hasError: true, error: error, info: info });
  }

  render(): {} {
    if (this.state.hasError) {
      return (
        <div id="errorModal" className="modal">
          <div className="modal-content">
            <span className="close">&times;</span>
            <h2>Application Crash</h2>
            <p>Error encountered in application.</p>
            {this.state.error}
          </div>
        </div>
      );
    }

    // Render children if no error
    return this.props.children;
  }
}

误差边界 https://reactjs.org/docs/error-boundaries.html旨在捕获渲染期间、生命周期方法以及其下方整个树的构造函数中的错误。

如果你想全局捕获未处理的 Promise 错误(而不是直接在组件中处理它),你可以使用window.onunhandledrejection https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent.

window.onunhandledrejection = function(e) {
  console.log(e.reason);
}

但默认情况下并非所有浏览器都支持它。

小黑客解决方案是打电话this.setState(() => { throw err; }); in catch你的承诺。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

componentDidMount 生命周期方法中子组件抛出的错误未在错误边界中捕获 的相关文章

随机推荐