React 的渲染一旦抛出未捕获错误,整个组件树会整个卸载——用户看到的就是白屏。错误边界是实现了 static getDerivedStateFromError 或 componentDidCatch 的类组件,它的子树发生渲染错误时被触发,把错误记下来并展示降级 UI,其余区域照常运行。
注意捕获范围:错误边界能捕获渲染、生命周期和子组件构造函数里的错误,但事件回调、setTimeout、异步请求里的错误捕不到——那些要用 try/catch 或 window 级监听处理。函数组件目前仍只能通过包装成类组件来实现,react-error-boundary 库是社区通用方案。
import React from 'react'; class Boundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; // 渲染出错时切换为降级 UI } componentDidCatch(error) { console.error('上报错误:', error); } render() { if (this.state.hasError) return <h3>模块开小差了,请刷新重试</h3>; return this.props.children; } } export default function App() { return <Boundary><Wigdet /></Boundary>; }