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

Expo Router报错:挂载Root Layout组件前尝试导航的问题求助

问题:Expo Router 2 点击跳转时报错 "Attempted to navigate before mounting the Root Layout component"

使用 Expo SDK-49 和 Expo Router 2 创建应用,修改自官方 tabs 模板,index 页面可正常渲染,但点击"Go to about"链接时触发如下错误:

Attempted to navigate before mounting the Root Layout component. Ensure the Root Layout component is rendering a Slot, or other navigator on the first render

错误原因

  1. Root Layout 未注册初始路由:_layout.js中的Stack组件只配置了about和details路由的Screen,缺少初始路由index的注册,导致导航栈无法正确管理初始页面。
  2. 加载阶段返回 null:当字体未加载完成时,Root Layout 返回null,此时导航根组件并未挂载,后续的导航操作会触发框架的前置检查错误。

解决方案

1. 在 Stack 中添加 index 路由的 Screen 配置

将index路由注册到导航栈中,确保初始页面被导航系统接管。

2. 替换加载阶段的返回值

不要返回null,改为返回一个空的View(或加载占位组件),保证导航根组件始终存在。

修改后的 _layout.js 代码

import FontAwesome from '@expo/vector-icons/FontAwesome';
import { useFonts } from 'expo-font';
import { SplashScreen, Stack, View } from 'expo-router';
import { useEffect } from 'react';
import { useColorScheme } from 'react-native';

export {
  ErrorBoundary,
} from 'expo-router';

export const unstable_settings = {
  initialRouteName: 'index',
};

SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const colorScheme = useColorScheme();

  const [loaded, error] = useFonts({
    SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
    ...FontAwesome.font,
  });

  useEffect(() => {
    if (error) throw error;
  }, [error]);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  // 加载阶段返回空View,而非null
  if (!loaded) {
    return <View />;
  }

  return (
    <Stack screenOptions={{ headerShown: false }}>
      {/* 添加index路由的Screen配置 */}
      <Stack.Screen name="index" options={{}} />
      <Stack.Screen name="about" options={{}} />
      <Stack.Screen name="details" options={{}} />
    </Stack>
  );
}

验证修改

修改完成后重新运行应用,index页面加载完成后点击"Go to about"链接,即可正常跳转到about页面,不会再触发导航错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:05:20