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

使用RTK Query拦截中间件无效,请求日志无法输出

问题原因及解决办法

你遇到的问题根源是:把日志中间件加到了createApi的middleware配置项里,但这个选项是RTK Query内部用来管理自身逻辑(比如缓存、标签失效)的中间件链,根本不会执行你的日志代码。

解决方法一:包装BaseQuery(推荐)

直接在发起请求的baseQuery层面添加日志,这是最直接的方式,每个请求都会经过这里:

// 假设你的baseQuery是fetchBaseQuery,先定义它
const baseQuery = fetchBaseQuery({ baseUrl: "/api" });

// 包装baseQuery,添加日志逻辑
const loggedBaseQuery = async (args, api, extraOptions) => {
  console.log("Request is being made:", args);
  const result = await baseQuery(args, api, extraOptions);
  console.log("Response received:", result);
  return result;
};

export const apiSlice = createApi({
  baseQuery: loggedBaseQuery, // 使用包装后的baseQuery
  tagTypes: ["Products", "Pages"],
  endpoints: () => ({}),
});

解决方法二:通过Redux Store中间件拦截请求

如果想在Store层面监听RTK Query的请求/响应Action,可以写一个Store中间件,识别RTK Query的Action类型:

const loggingMiddleware = (store) => (next) => (action) => {
  // 匹配请求发起的pending Action
  if (action.type.startsWith(apiSlice.reducerPath) && action.type.endsWith("/pending")) {
    console.log("Request is being made:", action.meta.arg);
  }
  // 匹配请求完成的fulfilled/rejected Action
  if (action.type.startsWith(apiSlice.reducerPath) && (action.type.endsWith("/fulfilled") || action.type.endsWith("/rejected"))) {
    console.log("Response received:", action.payload);
  }
  return next(action);
};

// 在Store中添加这个中间件
const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    auth: authSlice,
    header: headerSlice,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(loggingMiddleware, apiSlice.middleware),
  devTools: true,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:48:17