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

使用RTK Query时baseQueryWithReauth中extraOptions为何未定义?

问题:RTK Query中extraOptions无法传递到自定义baseQueryWithReauth函数

我正在使用Redux-Toolkit (RTK) Query结合fetchBaseQuery和自定义baseQueryWithReauth函数处理认证,用于检查认证状态并在必要时刷新令牌。但实际运行时,login请求设置的extraOptions在baseQueryWithReauth中为undefined,导致登录逻辑出错。


相关代码

baseQuery.js

import { fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { authApiSlice } from "~/features/api/authApiSlice";

// Create a base query instance
const baseQuery = fetchBaseQuery({
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  credentials: "include",
  prepareHeaders: (headers) => {
    headers.set("x-api-key", localStorage.getItem("apiKey") || '');
    return headers;
  },
});

const baseQueryWithReauth = async (args, api, extraOptions) => {
  console.log('Base Query Args:', args);
  console.log('Extra Options:', extraOptions);

  const shouldSkipAuth = extraOptions?.skipAuth || false;

  let result = await baseQuery(args, api, extraOptions);

  if (!shouldSkipAuth && result.error && result.error.status === 401) {
    const refreshResult = await api.dispatch(
      authApiSlice.endpoints.refreshToken.initiate()
    );

    if (refreshResult.data) {
      result = await baseQuery(args, api, extraOptions);
    } else {
      return refreshResult;
    }
  }

  return result;
};

export { baseQueryWithReauth as baseQuery };

authApiSlice.js

import { createApi } from "@reduxjs/toolkit/query/react";
import { baseQuery } from "~/services/api/baseQuery";

export const authApiSlice = createApi({
  reducerPath: "authApi",
  baseQuery,
  endpoints: (builder) => ({
    login: builder.mutation({
      query: ({ email, password }) => ({
        url: `/auth/login`,
        method: "POST",
        body: { email, password },
        extraOptions: { skipAuth: true }, // Skip auth for login
      }),
    }),
    refreshToken: builder.mutation({
      query: () => ({
        url: `/auth/refresh-token`,
        method: "POST",
      }),
    }),
  }),
});

export const { useLoginMutation } = authApiSlice;

Login.jsx

const [login] = useLoginMutation();

const handleLogin = async (email, password) => {
  try {
    const result = await login({ email, password }).unwrap();
    console.log('Login result:', result);
  } catch (err) {
    console.error('Login error:', err);
  }
};

已尝试的操作

  • 日志调试:在baseQueryWithReauth中打印extraOptions以验证是否正确传递。
  • 端点配置:在authApiSlice的login端点中配置了extraOptions,用于跳过认证逻辑。

预期结果

  • login请求设置的extraOptions能在baseQueryWithReauth函数中获取到,从而跳过login请求的认证逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 05:26:10