Vize

script/no-async-in-computed

禁止计算属性中的异步函数。

默认严重程度 预设 自动修复 选项
error essential, happy-path, ecosystem, nuxt, opinionated 不支持 无

适用范围:Vue SFC 中的 JS/TS 脚本;示例展示对应的 Options API 或 script setup 形式。

错误示例

computed getter 使用 async,因此 fetch 产生 Promise,而不是同步派生的计算值。

<script setup lang="ts">
import { computed } from "vue";
const data = computed(async () => {
  const response = await fetch("/api/data");
  return response.json();
});
</script>

正确示例

异步 fetch 移到 watch,将结果存入 data.value。清理逻辑中止旧请求,并阻止失效回调写入过期结果;不再存在异步计算 getter。

<script setup lang="ts">
import { ref, watch } from "vue";
const query = ref("");
const data = ref<unknown>(null);
watch(query, async (value, _oldValue, onCleanup) => {
  const controller = new AbortController();
  let active = true;
  onCleanup(() => { active = false; controller.abort(); });
  const response = await fetch(`/api/data?q=${encodeURIComponent(value)}`, { signal: controller.signal });
  const next: unknown = await response.json();
  if (active) data.value = next;
});
</script>

配置(Vite+)

import { defineConfig } from "@vizejs/vite-plugin/vite-plus";

export default defineConfig({}).withVue({
  linter: {
    "preset": "incremental",
    "rules": {
      "script/no-async-in-computed": "error"
    }
  },
});

然后运行 vp run lint。

相关页面