> ## Content Index
> Fetch the complete content index at: https://blog.anthea.day/llms.txt
> Use this file to discover other available public pages before exploring further.

# React 初心者大補帖（2）：React Query 如何測試 onError
- URL: https://blog.anthea.day/series-react-beginner-2/
- Published: 2025-05-29T07:59:27.000Z
- Updated: 2026-11-07T20:07:48.000Z
- Author: Anthea / 芫荽
- Tags: #Migrated-1792241843742, #Import 2026-10-17 12:57, Coding, React 初心者大補帖

最近在幫一個有使用到 react-query 的元件寫測試時遇到一個狀況：

![](https://blog.anthea.day/content/images/2026/10/1-bp3yg_ewqnmdfvto1hpp_a.png)

可以看到在上面的程式碼中，我有針對 error 做一些處理，因此我想寫個測試確認當我的 API 回傳錯誤後有正確的被處理：

![](https://blog.anthea.day/content/images/2026/10/1-kgdazjbnhtcefzbhtplwta.png)

但當我這執行測試後，卻發現測試執行不過：

![](https://blog.anthea.day/content/images/2026/10/1-kftmx4pqe5w5cpnhbzik8g.png)

可以從 console 中看到，錯誤是在驗證錯誤處理就被拋出了，在這裡下了 console log 之後可以看到目前的 result `isLoading = true` ：

![](https://blog.anthea.day/content/images/2026/10/1-dirscvgjfgbcyhr07ixkca.png)

#### 為什麼會這樣？

根據 [TanStack Query 官方文件](https://tanstack.com/query/latest/docs/framework/react/guides/query-retries?ref=blog.anthea.day) 的說明，react-query 預設會對失敗的請求重試三次，並使用指數退避（exponential backoff）策略，初始延遲為 1 秒，每次加倍，最多延遲 30 秒。

這就是為什麼我們的測試會噴掉的原因：

![](https://blog.anthea.day/content/images/2026/10/1-iifdsj4a94ko14wiqvl1fq.png)

#### 怎麼修正？

為了避免在測試中出現非預期的重試行為，可以在建立 QueryClient 時設定：

![](https://blog.anthea.day/content/images/2026/10/1-y8rhaqv_joqc0hj4wamgrw.png)

這樣除非在個別查詢中另行設定，不然預設就是禁用全域重試囉。