故障排除

修复 Expo 路由设置的常见问题。


React Native DevTools 中缺少文件或源映射

🌐 Missing files or source maps in React Native DevTools

如果你的 Chrome 开发者工具在其忽略列表中有排除项,就可能会发生这种情况。要解决此问题,请使用 React Native DevTools

🌐 This can happen if your Chrome DevTools has exclusions within its ignore list. To fix the issue, use React Native DevTools:

  1. 从在终端窗口中运行的开发服务器按 j 启动 React Native 开发工具
  2. 点击齿轮图标打开设置
  3. 扩展程序 下,点击 恢复默认并重新加载
  4. 再次打开设置,然后转到忽略列表标签
  5. 取消勾选 /node_modules/ 的任何排除项

EXPO_ROUTER_APP_ROOT 未定义

🌐 EXPO_ROUTER_APP_ROOT not defined

如果未定义 process.env.EXPO_ROUTER_APP_ROOT,你将看到以下错误:

🌐 If process.env.EXPO_ROUTER_APP_ROOT is not defined you'll see the following error:

Terminal
Invalid call at line 11: process.env.EXPO_ROUTER_APP_ROOT First argument of require.context should be a string.

当项目的 babel.config.js 中没有使用 Babel 插件 expo-router/babel 时,可能会发生这种情况。你可以尝试通过以下方法清除缓存:

🌐 This can happen when the Babel plugin expo-router/babel is not used in the project babel.config.js. You can try clearing the cache with:

Terminal
npx expo start --clear

或者,你可以通过在项目根目录创建一个 index.js 文件来绕过这个问题,文件内容如下:

🌐 Alternatively, you can circumvent this issue by creating an index.js file in the root of your project with the following contents:

index.js
import { registerRootComponent } from 'expo'; import { ExpoRoot } from 'expo-router'; // Must be exported or Fast Refresh won't update the context export function App() { const ctx = require.context('./app'); return <ExpoRoot context={ctx} />; } registerRootComponent(App);

然后,更新你应用的 package.json 主入口点:

🌐 Then, update your app's main entry point in package.json:

package.json
{ "main": "index.js" %%placeholder-start%%... %%placeholder-end%% }

不要使用此方法更改根目录 (app),因为它不会考虑在其他地方的使用情况。

require.context 未启用

🌐 require.context not enabled

当使用未启用上下文模块的自定义版本 @expo/metro-config 时,可能会发生这种情况。Expo Router 需要项目的 metro.config.js 使用 expo-router/metro 作为默认配置。删除 metro.config.js,或扩展 expo/metro-config。有关更多信息,请参阅 自定义 metro

🌐 This can happen when using a custom version of @expo/metro-config that does not enable context modules. Expo Router requires the project metro.config.js to use expo-router/metro as the default configuration. Delete the metro.config.js, or extend expo/metro-config. See Customizing metro for more information.

缺少后退按钮

🌐 Missing back button

如果你设置了一个模态窗口或其他预期有返回按钮的屏幕,那么你需要在路由的布局中添加 unstable_settings 来确保初始路由已配置。初始路由在移动应用中有些独特,在系统中显得不太顺畅 —— 改进正在进行中。

🌐 If you set up a modal or another screen that is expected to have a back button, then you'll need to add unstable_settings to the route's layout to ensure the initial route is configured. Initial routes are somewhat unique to mobile apps and fit awkwardly in the system — improvements pending.

app/_layout.tsx
export const unstable_settings = { initialRouteName: 'index', };