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

Vue 3中调用数组find方法报错:Cannot read properties of null (reading 'find')

问题分析与解决

错误原因

报错Uncaught (in promise) TypeError: Cannot read properties of null (reading 'find')的核心原因是调用.find()的对象为null,也就是weatherResponse.value在执行代码时不是预期的数组,而是null。

可能的触发场景:

  • weatherResponse变量在其他逻辑中被意外赋值为null;
  • 若使用Vue3 Composition API,代码中this.$store.commit的写法错误,this指向异常可能间接导致响应式变量状态异常;
  • 未处理API返回数据中location为null的情况(虽不直接触发find报错,但会引发后续逻辑问题)。

修复代码

import { ref } from 'vue'
import { useStore } from 'vuex' // 若使用Vuex需引入

const found = ref(null); // 存储找到的匹配元素,初始为null
const weatherResponse = ref([]);
const store = useStore(); // 获取Vuex store实例

function getLocation() {
  console.log("SETTING LOCATION");
  navigator.geolocation.getCurrentPosition((position) => {
    console.log(`Lat: ${position.coords.latitude}, Lon: ${position.coords.longitude}`);
    if (position.coords.latitude && position.coords.longitude) {
      axios.get(`https://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${Math.round(position.coords.latitude)},${Math.round(position.coords.longitude)}&aqi=no`)
        .then((response) => {
          // 确保weatherResponse.value始终是数组
          if (!Array.isArray(weatherResponse.value)) {
            weatherResponse.value = [];
          }

          // 校验API返回的location是否存在
          if (!response.data?.location) {
            console.warn('API返回数据中缺少location信息');
            return;
          }

          // 查找是否已有同名城市
          found.value = weatherResponse.value.find(item => 
            item.location?.name === response.data.location.name
          );

          // 无重复且无指定错误时存入数组
          if (response.data?.error?.code !== 1006 && !found.value) {
            weatherResponse.value.push(response.data);
            store.commit("addToList", response.data);
            console.log(weatherResponse.value);
          }
        })
        .catch(err => {
          console.error('天气API请求失败:', err);
        })
    }
  },
  (error) => {
    console.log(error.message);
  })
}

关键修复点

  1. 保障数组有效性:在调用find前增加数组类型检查,若变量被意外改为非数组则重置为空数组;
  2. 修正Vuex调用逻辑:Composition API中需用useStore()获取store实例,替代错误的this.$store;
  3. 增加数据校验:提前检查API返回的location字段,避免后续读取name时触发新错误;
  4. 完善异常捕获:为axios请求添加catch处理,避免请求失败导致代码中断;
  5. 明确变量语义:find返回匹配元素或undefined,将found初始值设为null更贴合逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:10:34