script/no-async-in-computed
Disallow async functions in computed properties.
| Default severity | Presets | Automatic fix | Options |
|---|---|---|---|
error |
essential, happy-path, ecosystem, nuxt, opinionated |
No | None |
Applies to: JS/TS scripts in Vue SFCs; examples show the relevant Options API or script setup form.
Bad
The computed getter is async, so the fetch produces a Promise instead of a synchronously derived computed value.
<script setup lang="ts">
import { computed } from "vue";
const data = computed(async () => {
const response = await fetch("/api/data");
return response.json();
});
</script>
Good
The asynchronous fetch moves into watch and stores its result in data.value. Cleanup aborts the old request and prevents an inactive callback from writing a stale result; no async computed getter remains.
<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>
Configuration (Vite+)
import { defineConfig } from "@vizejs/vite-plugin/vite-plus";
export default defineConfig({}).withVue({
linter: {
"preset": "incremental",
"rules": {
"script/no-async-in-computed": "error"
}
},
});
Then run vp run lint.