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

Vue/NUXT调用Vuex时出现Cannot read properties of undefined (reading 'commit')错误求助

问题解决:Cannot read properties of undefined (reading 'commit') & 相关逻辑修正

核心错误点分析

  1. 混淆Vuex的commit与dispatch:你在组件里用commit调用fetchCity,但fetchCity是action而非mutation。commit仅用于触发mutation,action需要用dispatch调用,这是触发commit未定义错误的直接原因。
  2. 未导入axios:store的action中使用了axios但未导入,会导致请求失败。
  3. 模板与computed属性不匹配:模板渲染{{ lat }},但computed定义的是coordinates,导致页面无法正确显示纬度。
  4. 未处理API请求异常:若输入城市不存在,response.data[0]会是undefined,直接访问.lat会触发新错误。

修正后的代码

1. index.vue 修正

<template>
  <div>
    <h1>APP NAME</h1>
    <form @submit.prevent="sendCityName()">
      <label for="query">输入城市名:</label>
      <input 
        type="text"
        id="query"
        v-model="cityName"
        placeholder="比如:Beijing"
      >
      <button type="submit">获取经纬度</button>
    </form>
    <h3>纬度:{{ lat }}</h3>
    <h3>经度:{{ lon }}</h3>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      cityName: ''
    }
  },
  computed: {
    // 用mapState直接映射state中的lat和lon,更简洁
    ...mapState(['lat', 'lon'])
  },
  methods: {
    sendCityName() {
      // 调用action必须用dispatch,而非commit
      this.$store.dispatch('fetchCity', this.cityName)
    }
  },
}
</script>

2. store.js 修正

import axios from 'axios' // 必须导入axios依赖

export const state = () => ({
    lat: '',
    lon: ''
})
  
export const mutations = {
    SET_LAT(state, payload){
      state.lat = payload
    },
    SET_LON(state, payload){
      state.lon = payload
    }
}
  
export const actions = {
    async fetchCity({ commit }, cityName) {
      try {
        const response = await axios.get(
          `https://api.openweathermap.org/geo/1.0/direct`, {
            params: {
              appid: "xxxxxxx", // 替换为你的OpenWeatherMap API密钥
              q: cityName,
            }
          }
        )
        if (response.data.length > 0) {
          commit('SET_LAT', response.data[0].lat);
          commit('SET_LON', response.data[0].lon);
        } else {
          alert('未找到该城市,请检查输入');
          commit('SET_LAT', '');
          commit('SET_LON', '');
        }
      } catch (error) {
        console.error('请求失败:', error);
        alert('获取经纬度失败,请稍后重试');
      }
    },
};

额外说明

  • 确保已通过npm install axios或yarn add axios安装axios依赖。
  • 替换store中appid的值为你的真实OpenWeatherMap API密钥,否则请求会被拒绝。
  • 添加try/catch和数组长度判断,可避免输入错误或网络问题导致的页面崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:15:56