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

Vite替代CRA后RTK Query代理配置失效及useGetCustomersQuery报错求助

解决Vite代理+RTK Query报错问题

一、修正Vite代理配置

你的Vite代理配置缺少跨域必需的changeOrigin参数,同时可根据需求添加路径重写规则。修改vite.config.js如下:

export default defineConfig({
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        changeOrigin: true,
        // 若后端接口无/api前缀,开启此行可去掉请求中的/api前缀
        // rewrite: (path) => path.replace(/^\/api/, '')
      },
    },
  },
});

配置后,请求/api/customers会被转发到http://localhost:3000/customers,匹配你的json server接口地址。

二、排查RTK Query报错

useGetCustomersQuery is not a function or its return value is not iterable错误和代理无关,是RTK Query的定义或使用问题,按以下步骤排查:

  1. 确认hook生成与导出
    检查apiSlice的定义,确保正确生成并导出hook:

    import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
    
    export const customersApi = createApi({
      reducerPath: 'customersApi',
      baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
      endpoints: (builder) => ({
        getCustomers: builder.query({
          query: () => '/customers',
        }),
      }),
    });
    
    // 自动生成的hook命名规则:use[EndpointName]Query
    export const { useGetCustomersQuery } = customersApi;
    
  2. 修正hook调用方式
    RTK Query的query hook返回对象而非数组,不能用数组解构:

    // 正确用法
    const { data: customers, error, isLoading } = useGetCustomersQuery();
    
    // 错误用法(会触发not iterable报错)
    // const [customers] = useGetCustomersQuery();
    
  3. 检查Redux Store配置
    必须在store中注册apiSlice的reducer和middleware:

    import { configureStore } from '@reduxjs/toolkit';
    import { customersApi } from './features/customers/customersApi';
    
    export const store = configureStore({
      reducer: {
        [customersApi.reducerPath]: customersApi.reducer,
      },
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(customersApi.middleware),
    });
    

三、验证代理有效性

启动Vite和json server后,在浏览器控制台查看网络请求:

  • 可见请求地址为http://localhost:5173/api/customers(Vite默认端口)
  • 实际转发目标为http://localhost:3000/customers,返回正确数据则代理生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:52:33