React错误边界为什么在函数组件里没生效?

轩辕潇郡 阅读 47

在函数组件里用类组件做错误边界,报错时页面直接崩溃了,没触发fallback UI。之前在类组件里用没问题,这次按文档改成函数组件包裹试试,代码这样写的:


class ErrorBoundary extends React.Component {
  state = { hasError: false };
  componentDidCatch() { this.setState({ hasError: true }); }
  render() { return this.state.hasError ? 

出错啦

: this.props.children; } } function App() { throw new Error('测试错误'); return
正常内容
; } // 使用时是这样嵌套的: <ErrorBoundary> <App /> </ErrorBoundary>

折腾了半天没搞定,控制台直接显示红色错误界面,边界组件根本没捕获到。是不是React新版本有什么变化?

我来解答 赞 10 收藏
二维码
手机扫码查看
1 条解答
百里子荧
问题出在 componentDidCatch 的写法不对,应该接收两个参数。而且 React 的错误边界在函数组件里直接崩溃是正常行为,错误边界只能捕获子组件的错误,不能捕获自己内部的。

修正后的代码:
class ErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch(error, info) { this.setState({ hasError: true }); }
render() { return this.state.hasError ? <div>出错啦</div> : this.props.children; }
}

function ErroneousComponent() {
throw new Error('测试错误');
return null;
}

function App() {
return (
<ErrorBoundary>
<ErroneousComponent />
</ErrorBoundary>
);
}


把抛错逻辑放到单独的子组件里,不要在 App 里直接抛错。
点赞 8
2026-02-02 16:25