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

Nuxt3串联调用两个API获取天气数据时报错如何解决

问题根源

你这段代码跑不通是几个写法错误叠加导致的:

  • 链式调用写法错误:useAsyncData本身是返回Promise的组合式函数,await useAsyncData(...)会直接返回{ data, pending, error }结构的结果。你在语句末尾追加.then(),会导致前面的解构const {data: locationdata}拿到的是then回调的返回值——你写的then回调里没有return任何内容,实际返回undefined,直接触发终端报的「解构undefined属性」错误。
  • 请求时序错误:两个useAsyncData是同级await执行的,第二个天气接口请求不会等第一个地理编码接口请求完成、给lat/lon/timezone赋值后再触发,发起请求时三个变量还是初始的null/空值。
  • ref取值错误:模板字符串里直接写${lat}拿到的是ref响应式实例,不是ref中存储的实际值,必须取.value才能拿到真实的经纬度、时区参数。
  • 接口结构理解错误:open-meteo地理编码接口返回的位置数据存放在results数组中,不是直接挂在响应根级,直接取res.data.value.latitude根本读不到对应属性。

你之前直接从路由参数取经纬度的代码能正常运行,是因为路由参数是同步可拿到的值,useFetch发起请求时参数已经是现成的,不存在异步等待的时序问题。

修正后代码

把两个串行请求合并到同一个useAsyncData里处理,从根源上避免时序和解构问题:

<script setup>
const route = useRoute()
const id = route.params.id

const { data: weatherdata, pending, error } = await useAsyncData(`city-forecast-${id}`, async () => {
  // 第一步:请求地理编码接口拿到经纬度、时区
  const locationRes = await $fetch(`https://geocoding-api.open-meteo.com/v1/get?id=${id}`)
  const targetLocation = locationRes.results?.[0]
  if (!targetLocation?.latitude || !targetLocation?.longitude) {
    throw new Error('未查询到对应城市的地理信息')
  }
  const { latitude, longitude, timezone } = targetLocation

  // 第二步:用拿到的地理参数请求天气预报接口
  return $fetch('https://api.open-meteo.com/v1/forecast', {
    params: {
      latitude,
      longitude,
      hourly: 'temperature_2m,relativehumidity_2m,surface_pressure,precipitation,weathercode,windspeed_10m,winddirection_10m,windgusts_10m',
      current_weather: true,
      windspeed_unit: 'kn',
      timezone
    }
  })
})
</script>

<template>
  <pre><code>{{ weatherdata }}</code></pre>
</template>

注意:这里给useAsyncData的key拼接了城市id,避免切换不同城市页面时命中旧的缓存数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:18:24