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

React Native Expo报错:无法读取undefined的watchPosition属性

解决Expo中使用navigator.geolocation.watchPosition报错的问题
  • 问题根源:你在Expo项目中混用了原生navigator.geolocation API和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控制触发更新的移动距离
    • 必须在权限申请通过后再启动监听,确保流程合法
    • 添加监听清理逻辑,防止组件卸载后出现内存泄漏

内容的提问来源于stack exchange,提问作者Laplace's Code

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:30:00