---
title: "给 React 加上错误边界并记录它漏掉的错误"
description: "React 错误边界（error boundary）会捕获渲染期间的错误并显示后备 UI。这里有类组件写法、它漏掉的错误，以及把每个错误发到 LogBrew 的方法，全部在 React 19.3 上实测。"
canonical: "https://logbrew.co/zh-Hans/guides/react-error-boundary"
last_updated: "2026-11-21"
---

# 给 React 加上错误边界并记录它漏掉的错误

React 错误边界（error boundary）会捕获渲染期间的错误并显示后备 UI。这里有类组件写法、它漏掉的错误，以及把每个错误发到 LogBrew 的方法，全部在 React 19.3 上实测。

2026年11月21日 用 React 19.3.1、Vite 8.3.8、Chrome 156、@logbrew/react 0.1.6、@logbrew/sdk 0.1.47和logbrew CLI 0.1.96 实测

作者 [Furkan Erday](https://github.com/furkanerday). Furkan Erday 是 LogBrew 的创始人，每天用 Claude Code 和 Codex 开发 LogBrew。

Canonical: https://logbrew.co/zh-Hans/guides/react-error-boundary

## 哪些 React 错误会显示后备 UI 并到达 LogBrew

| 错误抛出的位置 | 显示后备 UI | LogBrew 中的问题 |
| --- | --- | --- |
| 渲染，位于 `LogBrewErrorBoundary` 内 | 是 | 是 |
| `useEffect`，位于边界内 | 是 | 是 |
| 渲染，没有边界 | 否，根节点为空 | 是，来自根节点选项 |
| `onClick` 处理函数 | 否 | 否 |
| 异步处理函数，`await` 之后 | 否 | 否 |
| 使用 `captureReactError()` 的 `onClick` | 否 | 是 |

在 1 个使用 React 19.3.1 和 @logbrew/react 0.1.6 的 Vite 生产构建里触发的 6 个错误。

## 编写错误边界

### 把边界写成类组件

React 没有对应的 Hook，所以错误边界是一个类组件。`getDerivedStateFromError` 会在下一次渲染时切换到后备 UI。`componentDidCatch` 会收到错误和 `info.componentStack`，也就是抛出错误的组件之上的组件列表。

```bash
import { Component } from "react";

export class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.log("caught:", error.message);
    console.log("in:", info.componentStack.split("\n")[1].trim());
  }

  render() {
    if (this.state.error) return <p role="alert">Could not load the taps.</p>;
    return this.props.children;
  }
}
```

### 包住页面里可能出错的部分

`taps` 缺失时，`TapList` 读取 `taps.map`，于是在渲染期间抛出错误。边界显示了 `Could not load the taps.`，`Taproom` 标题仍然保留。在开发环境里，React 还打印了错误和 `The above error occurred in the <TapList> component`。

```bash
// TapList.jsx
export function TapList({ taps }) {
  return <ul>{taps.map((tap) => <li key={tap}>{tap}</li>)}</ul>;
}

// App.jsx
import { ErrorBoundary } from "./ErrorBoundary.jsx";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <main>
      <h1>Taproom</h1>
      <ErrorBoundary>
        <TapList />
      </ErrorBoundary>
    </main>
  );
}
```

输出

```text
caught: Cannot read properties of undefined (reading 'map')
in: at TapList (http://127.0.0.1:25174/guide/TapList.jsx:3:27)
```

### 事件处理函数里的错误会绕过边界

React 在渲染之外调用 `onClick`，所以边界始终没收到这个错误。按钮还留在页面上，浏览器打印了一个未捕获的错误。`await` 之后的错误也一样。

```bash
export function PourButton() {
  return (
    <button onClick={() => { throw new Error("pour failed"); }}>Pour</button>
  );
}

// main.jsx
createRoot(document.getElementById("root")).render(
  <ErrorBoundary>
    <PourButton />
  </ErrorBoundary>
);
```

输出

```text
Uncaught Error: pour failed
    at onClick (http://127.0.0.1:25174/guide/PourButton.jsx:6:10)
```

### 通过 state 把处理函数的错误交给边界

在处理函数里捕获错误，用 `setError` 存起来，然后在下一次渲染时抛出。这样边界就会显示后备 UI，并在 `componentDidCatch` 里收到错误。

```bash
import { useState } from "react";

export function SafePourButton() {
  const [error, setError] = useState(null);
  if (error) throw error;

  function pour() {
    try {
      throw new Error("pour failed");
    } catch (caught) {
      setError(caught);
    }
  }

  return <button onClick={pour}>Pour</button>;
}
```

输出

```text
caught: pour failed
in: at SafePourButton (http://127.0.0.1:25174/guide/SafePourButton.jsx:7:28)
```

### 没有边界时，React 会移除整棵树

当没有任何边界捕获渲染错误时，React 19 会卸载根节点。`root` 元素变成空的，标题也不见了。React 打印了错误，以及一条建议添加错误边界的警告。

```bash
import { createRoot } from "react-dom/client";
import { TapList } from "./TapList.jsx";

createRoot(document.getElementById("root")).render(
  <main>
    <h1>Taproom</h1>
    <TapList />
  </main>
);
```

输出

```text
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
An error occurred in the <TapList> component. Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.
```

## 把 React 错误发到 LogBrew

### 安装依赖包

`@logbrew/react` 提供 Provider、错误边界和根节点选项。用你的 LogBrew 项目里的浏览器密钥作为 `clientKey`。

```bash
npm install @logbrew/sdk @logbrew/react react
```

### 创建客户端和 transport

客户端会把事件放在队列里，直到你调用 `client.flush(transport)`。transport 必须返回 `{ statusCode }`。我们的 transport 直接返回 `fetch` 响应时，flush 以 `invalid transport response` 失败。把 `VITE_LOGBREW_ENDPOINT` 设为 `https://api.logbrew.co/v1/events`。我们发到的是本地 LogBrew 服务器。

```bash
import { createLogBrewReactClient } from "@logbrew/react";

export const client = createLogBrewReactClient({
  clientKey: import.meta.env.VITE_LOGBREW_CLIENT_KEY
});

export const transport = {
  async send(apiKey, body) {
    const response = await fetch(import.meta.env.VITE_LOGBREW_ENDPOINT, {
      method: "POST",
      headers: {
        authorization: `Bearer ${apiKey}`,
        "content-type": "application/json",
      },
      body
    });
    return { statusCode: response.status };
  }
};

export function send() {
  return client
    .flush(transport)
    .then((result) => console.log("sent", JSON.stringify(result)));
}
```

### 把 LogBrewErrorBoundary 放进 LogBrewProvider

`LogBrewErrorBoundary` 从 `LogBrewProvider` 获取客户端。没有 Provider 时，它显示了后备 UI 但什么都没发送，`onCaptureError` 收到了 `captureReactError requires a client`。`onError` 在捕获之后运行，所以在那里执行 flush。

```bash
import { LogBrewErrorBoundary, LogBrewProvider } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <LogBrewProvider client={client}>
      <LogBrewErrorBoundary
        fallback={({ error, resetError }) => (
          <div role="alert">
            <p>Could not load the taps: {error.message}</p>
            <button onClick={resetError}>Try Again</button>
          </div>
        )}
        onError={send}
      >
        <TapList />
      </LogBrewErrorBoundary>
    </LogBrewProvider>
  );
}
```

输出

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 捕获没有任何边界接住的错误

`createLogBrewReactRootOptions()` 为 `createRoot` 提供错误回调。它记录了没有边界时的渲染错误。它会跳过 `LogBrewErrorBoundary` 已经发送过的错误，所以每个错误只到达 1 次。

```bash
import { createRoot } from "react-dom/client";
import { createLogBrewReactRootOptions } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

createRoot(
  document.getElementById("root"),
  createLogBrewReactRootOptions(client, { onUncaughtError: send })
).render(<TapList />);
```

输出

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 用 captureReactError() 上报处理函数的错误

边界和根节点回调都收不到处理函数里的错误，所以要自己捕获它，再传给 `captureReactError()`。你传入的 `metadata` 会保留在问题上。

```bash
import { captureReactError } from "@logbrew/react";
import { client, send } from "./logbrew.js";

export function PayButton() {
  async function pay() {
    try {
      await Promise.resolve();
      throw new Error("payment declined");
    } catch (error) {
      captureReactError(client, error, { metadata: { action: "pay" } });
      send();
    }
  }

  return <button onClick={pay}>Pay</button>;
}
```

输出

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### 读回问题

我们用读取密钥读取项目。边界内的渲染错误和没有边界时的同一个错误都来自 `TapList.jsx`，所以它们合并成 1 个问题，共发生 2 次。处理函数的错误成了一个单独的问题。

```bash
logbrew issues --since 3h
```

输出

```text
Issues (2)
- 1613a62e-31a3-5045-a144-c9c593760bff unresolved error priority=medium React error: payment declined occurrences=1 users=unknown last_seen=2026-11-21T06:35:49.154Z service=unknown_service trace=2ca253b519dfa2866268889760e5f2a0 assignee=unassigned [unversioned / production]
- f9eb7448-fab2-5d52-82f3-592a3b680a08 unresolved error priority=medium React error: Cannot read properties of undefined (reading 'map') occurrences=2 users=unknown last_seen=2026-11-21T06:35:43.870Z service=unknown_service trace=225e883023acc9c768da676fedd8e2c1 assignee=unassigned [unversioned / production]
```

## 我们实测看到的结果

我们用 React 19.3.1 和 @logbrew/react 0.1.6 搭了 1 个 Vite 应用，配合本地 LogBrew 服务器在 Chrome 里运行每种情况。上面的输出来自 Vite 开发服务器。我们在生产构建里也跑了同样的情况，结果相同。

只有渲染期间和 `useEffect` 里的错误到达了边界。`onClick` 里和 `await` 之后的错误既没到达任何边界，也没到达根节点回调。只有 `captureReactError()` 发送了它们。

|  | `LogBrewErrorBoundary` | `onUncaughtError` |
| --- | --- | --- |
| 边界内的渲染错误 | 是 | 否 |
| 没有边界的渲染错误 | 否 | 是 |
| 事件处理函数里的错误 | 否 | 否 |

## 重置边界并重试

`LogBrewErrorBoundary` 的后备 UI 会收到 `resetError`，它会重新渲染子组件。如果子组件再次抛出错误，边界会再次显示后备 UI，并多发送 1 个事件。

所以重试之前先修复原因，比如重新加载数据。在我们的测试里，数据就绪后重试成功渲染了列表。

|  | 显示后备 UI | 发送事件 |
| --- | --- | --- |
| 第 1 次渲染错误 | 是 | 是 |
| `Try Again`，子组件再次抛出错误 | 是 | 是 |
| `Try Again`，子组件正常渲染 | 否 | 否 |

## LogBrew 记录了什么

每个 React 错误都会变成一个问题，标题是 `React error:` 加上错误消息。边界记录的机制是 `react.error_boundary`，带 `handled: true`。根节点选项记录的是 `react.uncaught_error`，带 `handled: false`。

LogBrew 按错误类型和第 1 个栈帧所在的文件来聚合 React 错误。在我们的生产构建里，5 个消息不同的 `Error` 事件，比如 `keg sensor offline` 和 `tap list not loaded`，来自同 1 个打包文件，于是成了 1 个问题。在开发环境里，每个组件都是单独的文件，所以问题仍然分开。

- `LogBrewErrorBoundary`
  - `mechanism`: `react.error_boundary`
  - `handled`: `true`
  - 问题: `React error: Cannot read properties of undefined (reading 'map')`
- `createLogBrewReactRootOptions()`
  - `mechanism`: `react.uncaught_error`
  - `handled`: `false`
  - 堆栈帧: 10
- `captureReactError()`
  - 问题: `React error: payment declined`
  - `metadata.action`: `pay`
  - 聚合键: `react.error:Error:…/HandlerButton.jsx`

## 常见问题

### React 里的错误边界是什么？

一个带有 `getDerivedStateFromError` 或 `componentDidCatch` 的类组件。子组件在渲染期间抛出错误时，React 会显示边界的后备 UI，并保留页面的其余部分。

### 能用 Hook 写错误边界吗？

不能。React 没有对应的 Hook，所以边界是一个类组件。写 1 次，或者直接用 `LogBrewErrorBoundary`，再把它包在函数组件外面。

### 为什么我的错误边界捕获不到错误？

错误是在渲染之外抛出的，通常在事件处理函数里或 `await` 之后。在那里捕获它并用 `captureReactError()` 上报，或者存进 state，在渲染期间抛出。

### 错误边界应该放在哪里？

包在页面里每个可能单独出错的部分外面，比如一个加载数据的列表，这样页面其余部分还能继续工作。在根节点附近也放 1 个，因为没有任何边界捕获的错误会移除整棵树。

### 怎么记录错误边界里的错误？

在 `componentDidCatch` 里发送，或者在 `LogBrewProvider` 里使用 `LogBrewErrorBoundary`。再给 `createRoot` 加上 `createLogBrewReactRootOptions()`，处理没有任何边界捕获的错误。

## 查看每个 React 错误及其组件栈

LogBrew 会连同组件栈记录每个 React 渲染错误，并把重复的错误聚合成 1 个问题。免费额度充足，无需绑卡。

[免费开始](https://logbrew.co/zh-Hans)

## 参考来源

- [React docs, Catching rendering errors with an Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [React docs, createRoot parameters](https://react.dev/reference/react-dom/client/createRoot#parameters)
- [reactjs/react.dev#8157](https://github.com/reactjs/react.dev/issues/8157)

## 更多智能体、Python、Node.js 与 React 指南

- [在 Claude Code 和 Codex 中添加 MCP 服务器](https://logbrew.co/zh-Hans/guides/mcp-server-claude-code-codex)
- [在 Claude Code 和 Codex 中使用 AGENTS.md](https://logbrew.co/zh-Hans/guides/agents-md)
- [解决 Claude overloaded 529 错误和 rate limit 429 错误](https://logbrew.co/zh-Hans/guides/claude-overloaded-rate-limit-error)
- [配置 Python 日志用对日志级别并捕获异常和回溯](https://logbrew.co/zh-Hans/guides/python-logging)
- [结构化日志用能按字段搜索的日志格式和日志级别](https://logbrew.co/zh-Hans/guides/structured-logging)
- [用 Pino 或 Winston 配置 Node.js 日志一个错误都不丢](https://logbrew.co/zh-Hans/guides/node-logging)
- [配置 Django 日志保留每个 500 错误的回溯信息](https://logbrew.co/zh-Hans/guides/django-logging)
- [配置 FastAPI 日志处理错误不丢失回溯](https://logbrew.co/zh-Hans/guides/fastapi-logging)
- [Trace ID 和 Span ID 的区别，用真实的 traceparent 请求头解读](https://logbrew.co/zh-Hans/guides/trace-id)
- [从完整消息和你自己的代码行入手修复 Minified React error #418 和 #185](https://logbrew.co/zh-Hans/errors/minified-react-error)
- [错误、日志、链路、指标和版本指南](https://logbrew.co/zh-Hans/guides)
