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

使用RTK-Query对接GitHub API时遇中间件未添加错误求助

解决RTK-Query对接GitHub API的中间件缺失报错

报错信息

Uncaught Error: Warning: Middleware for RTK-Query API at reducerPath "github/api" has not been added to the store. You must add the middleware for RTK-Query to function correctly!

问题代码

store配置文件

import {configureStore} from "@reduxjs/toolkit";
import {githubApi} from "./github/github.api";

export const store = configureStore({
  reducer: {
    [githubApi.reducerPath]: githubApi.reducer
  },
})

GitHub API定义文件

import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query/react";

export const githubApi = createApi({
  reducerPath: 'github/api',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://api.github.com/'
  }),
  endpoints: build => ({
    searchUsers: build.query<any, string>({
      query: (search: string) => ({
        url: `search/users`,
        params: {
          q: search
        }
      })
    })
  })
})

export const {useSearchUsersQuery} = githubApi

页面组件文件

import React from "react";
import {useSearchUsersQuery} from "../store/github/github.api";

export function HomePage() {
  const {isLoading, isError, data} = useSearchUsersQuery('anyname')

  return (
     <div>Home</div>
  )
}

问题原因

只在store中注册了RTK-Query的reducer,但没有添加对应的中间件。RTK-Query依赖专属中间件处理网络请求、缓存管理、状态同步等核心逻辑,缺失会导致功能失效并抛出上述报错。

修复方案

修改store配置文件,在configureStore的middleware选项中添加githubApi.middleware:

import {configureStore} from "@reduxjs/toolkit";
import {githubApi} from "./github/github.api";

export const store = configureStore({
  reducer: {
    [githubApi.reducerPath]: githubApi.reducer
  },
  // 新增中间件配置
  middleware: (getDefaultMiddleware) => 
    getDefaultMiddleware().concat(githubApi.middleware)
})

添加后,RTK-Query就能正常处理API请求和缓存逻辑了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:31:07