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

使用createAsyncThunk结合地理定位请求时始终返回undefined问题

问题解决:createAsyncThunk调用地理定位返回undefined

你的问题核心是navigator.geolocation.getCurrentPosition是基于回调的异步API,当前代码里的async函数没有等待它执行完成就直接结束,导致返回undefined;同时success回调里的返回值也没有传递到外层async函数中。

修正后的代码

export const fetchIataViaGeo = createAsyncThunk(
  'iata/fetchIataViaGeo',
  async (_, { rejectWithValue }) => {
    // 将getCurrentPosition包装为Promise,适配async/await语法
    const getPosition = () => {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      });
    };

    try {
      // 等待地理定位结果
      const position = await getPosition();
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;
      
      // 发起API请求并返回结果
      const res = await axios.get(
        `https://airlabs.co/api/v9/nearby?lat=${lat}&lng=${lng}&distance=45&api_key=...`
      );
      console.log(res.data.response.airports);
      return res.data.response.airports;
    } catch (err) {
      alert('Sorry, we could not find your location. Please enter manually.');
      // 传递错误信息到reducer处理
      return rejectWithValue(err.message);
    }
  }
);

关键修改点

  • 用Promise封装getCurrentPosition,让它可以被await,确保async函数等待地理定位完成后再执行后续逻辑
  • 使用try/catch统一处理地理定位失败或API请求失败的情况
  • 外层async函数直接返回API请求结果,让createAsyncThunk能正确获取到返回值
  • 用rejectWithValue传递错误信息,符合Redux Toolkit的错误处理规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:30:59