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

React Navigation调用navigation.navigate报TypeError未定义对象问题求助

报错原因排查
  • setTimeout 直接写在函数组件顶层作用域,没有用 useEffect 钩子包裹。函数组件每次渲染时都会执行顶层代码,此时如果组件还未完成挂载、navigation prop 还未被 react-navigation 正确注入,就会触发 navigation 为 undefined 的报错,同时多次重渲染还会生成多个重复定时器,存在内存泄漏风险。
  • 没有添加定时器清理逻辑,若组件在3秒内卸载,定时器回调仍然会执行,此时导航实例已经销毁也会触发同类报错。
修复方案

你可以选择任意一种方式修改 AccountScreen 代码即可解决问题:

方案1:基于props的navigation属性修复

import React, { useEffect } from "react";
import { AccountBackground,  AccountCover,  Title} from "../components/account.styles";
import { MaterialIcons } from "@expo/vector-icons";

export const AccountScreen = ({ navigation }) => {
  useEffect(() => {
    const timer = setTimeout(() => { 
      // 加可选链判断兜底,避免navigation未初始化时报错
      navigation?.navigate("Login");
    }, 3000);
    // 组件卸载时清理定时器
    return () => clearTimeout(timer);
  }, [navigation]);

  return (
        <AccountBackground>
           <AccountCover />
              <Title>Meals To Go</Title>
             <MaterialIcons name="navigate-next" size={48} color="black" />
        </AccountBackground>
  );
};

方案2:使用useNavigation钩子获取导航实例(更稳妥)

无需依赖props传递,直接从react-navigation全局获取导航实例:

import React, { useEffect } from "react";
import { useNavigation } from "@react-navigation/native";
import { AccountBackground,  AccountCover,  Title} from "../components/account.styles";
import { MaterialIcons } from "@expo/vector-icons";

export const AccountScreen = () => {
  const navigation = useNavigation();
  useEffect(() => {
    const timer = setTimeout(() => { 
      navigation.navigate("Login");
    }, 3000);
    return () => clearTimeout(timer);
  }, [navigation]);

  return (
        <AccountBackground>
           <AccountCover />
              <Title>Meals To Go</Title>
             <MaterialIcons name="navigate-next" size={48} color="black" />
        </AccountBackground>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:04