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

页面重载时如何延迟API请求至mockServiceWorker.js加载完成?

问题:Next.js中MSW重载页面时无法及时拦截RTK Query请求导致500错误

我正在使用Next.js开发前端应用,采用RTK Query进行API请求,使用MSW实现接口Mock。页面首次加载时mockServiceWorker.js已加载完成,Mock可正常拦截API请求;但通过浏览器重载页面时,API请求会先执行,MSW还未完成拦截,从而导致500错误。我尝试控制RTK Query的调用时机,也研究过mockServiceWorker.js等公共文件的加载时机,但尚未找到解决方案。

示例代码

src/pages/_app.tsx

import React, { useEffect } from 'react';

import { CacheProvider, EmotionCache } from '@emotion/react';
import { AppProps } from 'next/app';
import Head from 'next/head';

import { GlobalLayout } from '../components/globals/GlobalLayout';
import { Providers } from '../components/globals/Providers';
import createEmotionCache from '../createEmotionCache';
import '../styles/globals.css';

if (process.env.NODE_ENV !== 'production') {
  if (process.env.NEXT_PUBLIC_ENABLE_MOCK_SERVER) {
    const { worker } = require('./mocks/browser')
    worker.start()
  }
}

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

export interface MyAppProps extends AppProps {
  emotionCache?: EmotionCache;
}

export default function MyApp(props: MyAppProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

  useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement?.removeChild(jssStyles);
    }
  }, []);

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>Front Template</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
        <meta name="description" content="Front Template" />
      </Head>
       <Providers>
        <GlobalLayout>
          <Component {...pageProps} />
        </GlobalLayout>
      </Providers>
    </CacheProvider>
  );
}

src/pages/test.tsx

export default function Test() {
  const [fetch, { data }] = usePostApiFooMutation();
  useEffect(() => {
    fetch(args);
  }, [fetch, args]);
  return (
    <>
      <Button onClick={() => fetch(args)}>fetch</Button>
      <div>{JSON.stringify(data?.payload)}</div>
    </>
  );
}

环境信息

  • typescript: 4.5.2
  • react: 18.2.0
  • next: 13.4.3
  • @reduxjs/toolkit: 1.9.5
  • msw: 1.2.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:51:31