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

使用next/router和useEffect后404自动跳转首页致导航失效

问题根源

你的404页面代码存在两个核心问题:

  1. useEffect依赖time状态,每次倒计时更新都会重新执行effect,导致重复创建多个setInterval定时器,这些定时器会不断触发router.push('/'),重复的路由请求互相干扰,引发"Abort fetching component"错误。
  2. 未清理定时器,即使跳转到首页后,旧的定时器仍在后台运行,导致部分页面会被强制跳回首页。

修复后的404.jsx代码

import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import Head from "next/head";

export default function NotFound404() {
  
  const [time, setTime] = useState(3);
  const [tick, setTick] = useState(".");
  const router = useRouter();

  useEffect(() => {
    // 倒计时定时器:每秒更新100次时间
    const countdownTimer = setInterval(() => {
      setTime(prev => {
        const newTime = prev - 0.01;
        return newTime > 0 ? newTime.toFixed(2) : 0;
      });
    }, 10);

    // 打点动画定时器:每300ms更新一次
    const tickTimer = setInterval(() => {
      setTick(prev => prev.length < 3 ? prev + "." : "");
    }, 300);

    // 跳转定时器:仅执行一次3秒后跳转首页
    const redirectTimer = setTimeout(() => {
      router.push("/");
    }, 3000);

    // 组件卸载时清理所有定时器,避免内存泄漏和残留执行
    return () => {
      clearInterval(countdownTimer);
      clearInterval(tickTimer);
      clearTimeout(redirectTimer);
    };
  }, []); // 空依赖数组,仅组件挂载时执行一次

  return (
    <main>
      <Head>
        <title>Page not found</title>
      </Head>
      <div className="flex flex-col justify-center items-center h-[75vh] w-full gap-10">
        <h1 className="text-6xl italic font-bold font-mono text-center">404! NOT FOUND!!</h1>
      </div>
      <p className="font-mono italic text-center">
        Returning back in {time} seconds {tick}
      </p>
    </main>
  );
}

关键修复点说明

  • 用setTimeout替代setInterval执行跳转,确保仅触发一次路由跳转操作。
  • 将useEffect的依赖改为空数组,避免因time更新重复创建定时器。
  • 所有定时器都在组件卸载时通过clearInterval/clearTimeout清理,彻底杜绝残留逻辑干扰其他页面。
  • 倒计时更新改用函数式setTime(prev => ...),确保状态更新基于最新值,避免闭包陷阱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 15:57:30