Expo Web模式下AsyncStorage报window未定义错误求助
问题描述
尝试复现Supabase的Expo React Native官方示例,启动Expo应用的Web模式时触发错误,核心报错信息如下:
ReferenceError: window is not defined at getValue (/Users/dave/Documents/repos/eatyourfriend/node_modules/@react-native-async-storage/async-storage/lib/commonjs/AsyncStorage.js:63:26) at /Users/dave/Documents/repos/eatyourfriend/node_modules/@react-native-async-storage/async-storage/lib/commonjs/AsyncStorage.js:39:21
同时日志中还出现一系列API弃用警告(如shadow*样式属性、TouchableOpacity组件等)。
解决方案
1. 重新安装Expo兼容的AsyncStorage包
@react-native-async-storage/async-storage在Web环境下依赖Expo的适配层,直接用npm/yarn安装可能导致环境不兼容,执行以下命令重新安装:
expo install @react-native-async-storage/async-storage
2. 解决服务端渲染下的window未定义问题
expo-router默认启用服务端渲染(SSR),而AsyncStorage依赖浏览器环境的window对象,需在代码中做环境判断:
- 封装AsyncStorage调用,仅在客户端执行:
import AsyncStorage from '@react-native-async-storage/async-storage'; const getStoredData = async (key) => { if (typeof window === 'undefined') return null; return await AsyncStorage.getItem(key); };
- 或在组件中通过
useEffect延迟调用,确保在客户端渲染阶段执行:
import { useEffect, useState } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; export default function Home() { const [storedValue, setStoredValue] = useState(null); useEffect(() => { const fetchData = async () => { const value = await AsyncStorage.getItem('supabase-session'); setStoredValue(value); }; fetchData(); }, []); // 组件其余逻辑 }
3. 处理弃用警告(可选)
针对日志中的弃用提示,逐一替换为Web兼容的API:
- 替换
shadowColor/shadowOffset等样式为boxShadow(遵循Web CSS标准) - 用
style={{ userSelect: 'none' }}替代selectable={false} - 用
readOnly属性替代editable={false} - 用
Pressable组件替换TouchableOpacity - 用
role属性替代accessibilityRole,移除accessibilityDisabled和focusable属性
内容的提问来源于stack exchange,提问作者Dave Edelhart
相关产品推荐
相关产品推荐

