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

Vue.js中调用async函数fetchTasks报错:this.fetchTasks is not a function

问题解决:Uncaught (in promise) TypeError: this.fetchTasks is not a function

核心问题

你将fetchTasks和fetchTask这两个异步函数定义在了组件选项的根层级,而非methods对象内部。Vue组件仅会把methods中的函数挂载到组件实例(即this)上,根层级的自定义函数无法通过this访问,因此触发该错误。

修正后的完整代码

<template>
  <div class="container">
    <HeaderApp @toggle-add-task="toggleAddTask" title="Task Tracker" :showAddTask="showAddTask" />
    <div v-show="showAddTask">
      <AddTask @add-task="addTask" />
    </div>
    <TasksApp @toggle-reminder="toggleReminder" @delete-task="deleteTask" :tasks="tasks" />
  </div>
</template>

<script>
import HeaderApp from './components/HeaderApp'
import TasksApp from './components/TasksApp.vue'
import AddTask from './components/AddTask.vue'

export default {
  name: 'App',
  components: {
    HeaderApp,
    TasksApp,
    AddTask
  },
  data () {
    return {
      tasks: [],
      showAddTask: false
    }
  },
  methods: {
    toggleAddTask () {
      this.showAddTask = !this.showAddTask
    },
    addTask (task) {
      this.tasks = [...this.tasks, task]
    },
    deleteTask (id) {
      if (confirm('Are you sure?')) {
        this.tasks = this.tasks.filter((task) => task.id !== id)
      }
    },
    toggleReminder (id) {
      this.tasks = this.tasks.map((task) => task.id === id ? { ...task, reminder: !task.reminder } : task)
    },
    // 把两个异步函数移到methods内部
    async fetchTasks () {
      const res = await fetch('http://localhost:3000/tasks')
      const data = await res.json()
      return data
    },
    async fetchTask (id) {
      const res = await fetch(`http://localhost:3000/tasks/${id}`)
      const data = await res.json()
      return data
    }
  },
  async created () {
    this.tasks = await this.fetchTasks()
  }
}
</script>

关键说明

  • Vue 2组件中,所有自定义方法必须放在methods选项内,根层级仅支持Vue官方预设的选项(如data、created、computed等)
  • created钩子可以定义为异步函数,你原本的调用逻辑(await this.fetchTasks())是正确的,只需调整函数的位置即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:40:37