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

使用PokeAPI获取随机初代宝可梦时出现404错误求助

问题分析与修复方案

核心问题

  1. 调用方法未传参:Home组件中调用getOnePokemon()时未传入ID,导致请求URL变为https://pokeapi.co/api/v2/pokemon/undefined,触发404错误。
  2. 递归调用未返回结果:catch块中递归调用getOnePokemon但未返回异步操作的Promise,导致上层无法获取到有效数据。
  3. 名称替换不彻底:replace('-', " ")仅替换第一个横杠,无法处理类似nidoran-f这类含多个横杠的名称。

修复后的代码

1. Store.js 修正

import { defineStore } from 'pinia'
import axios from 'axios'

const serverHost = 'https://pokeapi.co/api/v2'

export const pokeStore = defineStore("pokemons", {
  state: () => ({
    pokemons: []
  }),
  actions: {
    async getOnePokemon(id) {
      // 未传ID时自动生成1-151的随机ID
      const targetId = id ?? Math.floor(Math.random() * 151) + 1;
      try {
        const response = await axios.get(`${serverHost}/pokemon/${targetId}`)
        const data = response.data;
        // 全局替换所有横杠为空格
        const formattedName = data.name.replace(/-/g, " ");
        const pokemon = {
          id: data.id,
          name: formattedName,
          image: data.sprites.front_default || data.sprites.front_shiny
        }
        return pokemon;
      } catch (error) {
        // 递归调用需返回Promise,确保上层能接收结果
        return this.getOnePokemon(Math.floor(Math.random() * 151) + 1);
      }
    },
  }
});

2. Home组件 修正

<script setup lang="ts">
import { ref } from 'vue'
import { pokeStore } from '../store/store'
const PokemonStore = pokeStore();

const allpokemonsIds = ref<any>()

async function GetPokemons() {
  try {
    // 无需传参,方法内部自动生成随机ID
    const response = await PokemonStore.getOnePokemon();
    allpokemonsIds.value = response;
    console.log(allpokemonsIds.value);
  } catch (error) {
    console.error('获取宝可梦失败:', error);
  }
}

GetPokemons()
</script>

关键修复说明

  • 自动生成随机ID:在store方法内处理ID生成,避免调用时漏传参数的问题。
  • 递归返回Promise:确保递归调用的异步结果能传递到上层组件。
  • 全局替换横杠:保证所有名称中的横杠都能转为空格。
  • 简化图片逻辑:用||直接取第一个可用的图片地址,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:10:27