钻石星辰4 2025-03-10 23:11 采纳率: 58.3%
浏览 7
已结题

react使用错误边界,应用依然崩溃,这是为什么?

react 中,我用类组件创建了一个错误边界,在子组件的 componentDidMount 中打印一个未声明的变量。能够捕获到错误,页面上能看见备用 ui 闪了一下,应用还是崩溃了。请问这是为什么?
index.js:

<MyErrorBoundary fallback={<p>Something went wrong!!!</p>}>
        <Snapshot />
</MyErrorBoundary>

errorBoundary.js:

import React from 'react';
import myLog from './utils/myLog';

class ErrorBoundary extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      hasError: false,
    }
  }

  static getDerivedStateFromError(error){
    console.log('getDerivedStateFromError');

    return {
      hasError: true,
    }
  }

  componentDidCatch(error, info){
    myLog('error', error);
    myLog('info', info);
    // console.error("Caught an error boundary", error, info);
  }

  render(){
    const {children, fallback} = this.props;
    const {hasError} = this.state;

    myLog('hasError', hasError);

    if(hasError){
      return fallback;
    }

    return children;
  }
}

export default ErrorBoundary;

snapshot:

componentDidMount(){
    // throw new Error('componentDidMount 出错了!');
    console.log(undefinedVariety);
  }

后来我尝试用 react-error-boundary,结果是一样的。
模块版本:
"react": "^16.13.1",
"@types/react": "^16.9.41",
"react-error-boundary": "^5.0.0",

  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2025-03-10 23:11
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    react 使用错误边界,应用依然崩溃,这是为什么?

    你使用了 React 的错误边界(Error Boundary),但是应用仍然崩溃了。这可能是因为错误边界只能捕获子组件中的错误,而不能捕获父组件中的错误。

    在你的情况中,你在子组件的 componentDidMount 中打印了一个未声明的变量,这个错误会导致整个应用崩溃,而不是只是子组件崩溃。错误边界只能捕获子组件中的错误,而不能捕获父组件中的错误。

    如果你想捕获父组件中的错误,可以使用 React 的 try-catch 语句来捕获错误。例如:

    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { error: null };
      }
    
      componentDidCatch(error, errorInfo) {
        this.setState({ error });
      }
    
      render() {
        if (this.state.error) {
          return (
            <div>
              <h2>Something went wrong.</h2>
              <details style={{ whiteSpace: 'pre-wrap' }}>
                {this.state.error.toString()}
              </details>
            </div>
          );
        }
        return this.props.children;
      }
    }
    

    在上面的代码中,我们使用 componentDidCatch 生命周期方法来捕获错误,并将错误信息存储在 state 中。如果错误发生,我们将渲染备用 UI,而不是崩溃应用。

    需要注意的是,错误边界只能捕获子组件中的错误,而不能捕获父组件中的错误。如果你想捕获父组件中的错误,需要使用 try-catch 语句或其他机制。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月29日
  • 创建了问题 3月10日