知海

规则:error-boundaries

ReactAPI 参考:ESLint 插件

error-boundaries

验证子组件中的错误应使用错误边界而不是 try/catch。

规则详情 {/rule-details/}

try/catch 代码块无法捕获 React 渲染过程中发生的错误。渲染方法或 hooks 中抛出的错误会沿着组件树向上冒泡。只有错误边界才能捕获这些错误。

无效用法 {/invalid/}

本规则的错误代码示例:

js 复制代码
// ❌ Try/catch won't catch render errors
function Parent() {
  try {
    return <ChildComponent />; // If this throws, catch won't help
  } catch (error) {
    return <div>Error occurred</div>;
  }
}

有效用法 {/valid/}

本规则的正确代码示例:

js 复制代码
// ✅ Using error boundary
function Parent() {
  return (
    <ErrorBoundary>
      <ChildComponent />
    </ErrorBoundary>
  );
}

故障排除 {/troubleshooting/}

为什么 linter 不让我把 use 包在 try/catch 中? {/why-is-the-linter-telling-me-not-to-wrap-use-in-trycatch/}

use hook 不会以传统方式抛出错误,它会让组件执行挂起(suspend)。当 use 遇到一个 pending Promise 时,它会挂起组件,让 React 显示 fallback。只有 Suspense 和错误边界能处理这些情况。linter 会警告不要在 use 周围使用 try/catch,以防止误解,因为 catch 块永远不会运行。

js 复制代码
// ❌ Try/catch around `use` hook
function Component({promise}) {
  try {
    const data = use(promise); // Won't catch - `use` suspends, not throws
    return <div>{data}</div>;
  } catch (error) {
    return <div>Failed to load</div>; // Unreachable
  }
}

// ✅ Error boundary catches `use` errors
function App() {
  return (
    <ErrorBoundary fallback={<div>Failed to load</div>}>
      <Suspense fallback={<div>Loading...</div>}>
        <DataComponent promise={fetchData()} />
      </Suspense>
    </ErrorBoundary>
  );
}

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。