API返回204时TanStack Query持续重复请求致浏览器冻结求助
解决方案:TanStack Query 因204响应无限重复请求
问题根源
当API返回204(No Content)状态码时,响应体为空。axios默认会尝试将响应解析为JSON,空字符串无法被JSON.parse解析,会抛出Unexpected end of JSON input错误。TanStack Query捕获到该错误后触发默认重试机制,进而引发无限重复请求。
解决步骤
1. 修改Axios请求配置,处理204响应
在自定义useQueryHook中调整axios请求配置,避免解析空响应体导致的错误:
import { useQuery } from "@tanstack/react-query"; import axios from "axios"; export const useQueryHook = (api: string, queryKey: string)=>{ return useQuery(queryKey, async() => { const response = await axios.get(api, { // 明确将204纳入成功状态码范围 validateStatus: (status) => status >= 200 && status < 300, // 自定义响应转换逻辑,跳过空响应体的JSON解析 transformResponse: (data) => { // 204响应体为空,直接返回null(或空数组/对象,按需调整) if (!data) { return null; } // 正常响应解析为JSON return JSON.parse(data); } }); // 返回处理后的数据,而非整个response对象 return response.data; }); }
2. 优化TanStack Query重试逻辑(可选)
如果需要更精细控制重试行为,可在useQuery中添加重试条件,仅在实际请求失败时重试:
export const useQueryHook = (api: string, queryKey: string)=>{ return useQuery(queryKey, async() => { // ... 上述axios请求代码 }, { // 仅在HTTP状态码>=400或网络错误时重试,最多3次 retry: (failureCount, error) => { if (error.response?.status >= 400) { return failureCount < 3; } // 204相关的解析错误不再触发重试 return false; } }); }
3. 验证CORS配置(可选)
检查后端CORS配置,确保204响应返回正确的Access-Control-Allow-Origin头。若缺少该头,浏览器会触发CORS错误,同样会导致TanStack Query重试。可补充明确允许GET方法:
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"http://localhost:5173", "https://test.net"}, AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept}, AllowMethods: []string{echo.GET}, // 明确允许GET请求方法 }))
验证修改
修改后,当API返回204时,axios会直接返回null(或你指定的空结构),TanStack Query将其视为有效数据,不会触发重试。可在组件中判断数据状态展示对应内容:
const { isLoading, data } = useQueryHook(api, "students"); if (isLoading) { return <h2>Loading...</h2>; } if (!data) { return <div>No data available</div>; } // 正常渲染数据逻辑
内容的提问来源于stack exchange,提问作者jeril
相关产品推荐
相关产品推荐

