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

如何在TypeScript中获取RTK Query的error.data?

在TypeScript中正确获取RTK Query的error.data

问题描述

控制台输出error时能看到如下结构:

{
    status: 401,
    data: "Invalid password"
}

但访问error.data时触发TypeScript错误:

类型“FetchBaseQueryError|SerializedError”上不存在属性“data”。类型“SerializedError”上不存在属性“data”。ts(2339)

完整代码:

const [login, { data, error }] = useLoginMutation()

const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (event) => {
    event.preventDefault()

    if (credential.user_email.trim() !== '' && credential.user_password.trim() !== '') {
        await login(credential)
    }
}

useEffect(() => {
    if (data !== undefined) {
        localStorage.token = data.token
    }
}, [data])

useEffect(() => {
    if (error !== undefined) {
        console.log(error.data) // 此处触发TS错误
    }
}, [error])

解决方案

RTK Query返回的error是联合类型:FetchBaseQueryError | SerializedError。其中只有FetchBaseQueryError包含data属性(对应后端返回的错误响应),SerializedError用于处理网络失败、序列化错误等场景,没有data字段。因此需要通过类型窄化告诉TypeScript当前error的具体类型。

方法1:使用in操作符直接判断

useEffect(() => {
    if (error !== undefined) {
        if ('data' in error) {
            console.log(error.data);
        }
    }
}, [error])

方法2:自定义类型守卫函数

import type { FetchBaseQueryError } from '@reduxjs/toolkit/query';

function isFetchBaseQueryError(error: unknown): error is FetchBaseQueryError {
    return typeof error === 'object' && error !== null && 'status' in error;
}

useEffect(() => {
    if (error !== undefined && isFetchBaseQueryError(error)) {
        console.log(error.data);
    }
}, [error])

方法3:使用RTK内置的类型守卫

如果使用较新版本的Redux Toolkit,可以直接导入官方提供的类型守卫函数:

import { isFetchBaseQueryError } from '@reduxjs/toolkit/query';

useEffect(() => {
    if (error !== undefined && isFetchBaseQueryError(error)) {
        console.log(error.data);
    }
}, [error])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:18:23