You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Query中如何在成功重新获取前保留错误状态

React Query 重试时保留错误状态直到请求成功的解决方案

你遇到的问题是React Query默认触发refetch时会立即重置isError为false,但error对象本身不会被清空——只有当新请求成功返回数据时,error才会被重置为null。利用这一点,不需要额外的useState就能实现重试时保留错误UI的需求。

核心解决方案:组合isRefetching与error状态判断

调整错误状态的判断逻辑,当初始请求失败(isError为true),或者**正在重试(isRefetching为true)且之前存在错误(error不为null)**时,继续显示错误组件,同时展示加载状态。

修改后的代码示例:

const { data, isLoading, isFetching, isError, error, refetch, isRefetching } = getUsers();

// 自定义错误状态判断:初始失败 或 重试中且有历史错误
const shouldShowErrorUI = isError || (isRefetching && error);

if (shouldShowErrorUI) {
    return (
        <div className='border border-neutral-200 py-8 px-4 rounded-md text-center'>
            <div>
                <Typography variant='base' as='h1' weight={500} className='text-black'>
                    Oh no, something went wrong!
                </Typography>
                <Typography variant='small' as='h1' weight={500} className='text-black'>
                    Sorry, we ran into an issue fetching the information. A quick retry might solve it.
                </Typography>
            </div>
            <div className='mt-4'>
                <Button impact='light' color='blue' onClick={() => refetch()} className='inline-flex px-4'>
                    {isFetching ? <Icon name='Loader' className='animate-spin' /> : 'Retry'}
                </Button>
            </div>
        </div>
    );
}

原理说明

  • React Query的error字段会在请求失败时被赋值,只有当新请求成功响应后才会被清空;
  • isRefetching专门标记当前是否处于重试/后台刷新状态,和初始加载的isLoading区分开;
  • 通过组合这两个状态,就能在重试过程中持续展示错误提示,同时让按钮显示加载动画,避免错误UI闪烁消失。

最佳实践

  1. 尽量复用React Query提供的内置状态,避免手动维护useState,减少状态不同步的风险;
  2. 如果需要区分初始加载和重试的加载状态,可以用isLoading判断初始加载,isRefetching判断重试过程;
  3. 若场景更复杂(比如需要保留多次错误信息),可以考虑自定义查询的onError回调,但大多数基础场景用上述状态组合即可满足需求。

内容的提问来源于stack exchange,提问作者Thore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 14:52:49