React Native Expo报错:无法读取undefined的watchPosition属性
问题根源:你在Expo项目中混用了原生
navigator.geolocationAPI和expo-location包,两者的权限体系、运行逻辑不兼容。expo-location申请的权限无法被原生navigator.geolocation识别,直接触发报错。修正方案:完全使用expo-location提供的
watchPositionAsync方法实现位置监听,它能和你已申请的权限无缝配合,修正后的代码如下:
import { useEffect, useState } from 'react'; import { Alert } from 'react-native'; import * as Location from 'expo-location'; const [location, setLocation] = useState(null); useEffect(() => { let locationSubscription; const setupLocation = async () => { // 请求前台位置权限 let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== "granted") { console.log("Please grant location permissions"); return; } // 获取初始位置 let currentLocation = await Location.getCurrentPositionAsync({}); setLocation(currentLocation); console.log(`latitude: ${currentLocation.coords.latitude}`); console.log(currentLocation); // 开启位置监听 locationSubscription = await Location.watchPositionAsync( { accuracy: Location.Accuracy.High, // 对应原enableHighAccuracy: true timeInterval: 1000, // 位置更新间隔(毫秒) distanceInterval: 0 // 移动指定距离后更新,0表示实时更新 }, (position) => { console.log(position); setLocation(position); }, (error) => { Alert.alert("Error", error.message); } ); }; setupLocation(); // 组件卸载时清理监听,避免内存泄漏 return () => { locationSubscription?.remove(); }; }, []);
- 关键说明:
- expo-location的
watchPositionAsync参数格式与原生API不同,用accuracy替代enableHighAccuracy,timeInterval控制更新频率,distanceInterval控制触发更新的移动距离 - 必须在权限申请通过后再启动监听,确保流程合法
- 添加监听清理逻辑,防止组件卸载后出现内存泄漏
- expo-location的
内容的提问来源于stack exchange,提问作者Laplace's Code
相关产品推荐
相关产品推荐

