Vize

vize:croquis/cf/watcheffect-async

为异步 watchEffect 处理失效清理,避免写入过期响应。

默认严重程度 自动修复 选项
error 无;请检查相关文件并应用修复 无针对单个诊断代码的选项;受支持的 CLI 诊断可覆盖严重程度

适用范围: 已分析的组件图,以及下方说明的受支持事实

适用范围与限制

这里的异步 watchEffect 没有失效清理,也没有防止过期响应的保护。Vue 支持 watchEffect 的清理;正确示例使用显式的 watch 来源,并取消已失效的工作。

共享项目文件

错误和正确示例都使用这些不变的文件。在项目中安装导入的包:Vue,以及示例中出现的 vue-router 或 Pinia。遵循版本特定的支持说明。入口根文件显式展示组件关系。

main.ts

import { createApp } from "vue";
import Root from "./SearchPage.vue";
createApp(Root).mount("#app");

index.html

<div id="app"></div>
<script type="module" src="/main.ts"></script>

api.ts

export interface Result { items: string[]; }
export async function load(query: string, options?: { signal?: AbortSignal }): Promise<Result> {
  const response = await fetch(`/search?q=${encodeURIComponent(query)}`, options);
  return response.json();
}

错误示例

此处的异步 watchEffect 没有失效清理,也没有防止过期响应的保护。异步 watchEffect 将隐式依赖收集与等待请求混合,且没有失效保护。

SearchPage.vue

<script setup lang="ts">
import { ref } from "vue";
import SearchResults from "./SearchResults.vue";

const query = ref("");
</script>

<template>
  <SearchResults :query="query" />
</template>

SearchResults.vue

<script setup lang="ts">
import { load, type Result } from "./api";
import { ref, watchEffect } from "vue";

const props = defineProps<{ query: string }>();
const result = ref<Result | null>(null);

watchEffect(async () => {
  result.value = await load(props.query);
});
</script>

正确示例

显式的 watch(() => props.query, ...) 声明来源、注册请求清理,并在失效后拒绝过期响应。

SearchPage.vue

<script setup lang="ts">
import { ref } from "vue";
import SearchResults from "./SearchResults.vue";

const query = ref("");
</script>

<template>
  <SearchResults :query="query" />
</template>

SearchResults.vue

<script setup lang="ts">
import { load, type Result } from "./api";
import { ref, watch } from "vue";

const props = defineProps<{ query: string }>();
const result = ref<Result | null>(null);

watch(
  () => props.query,
  async (value, _oldValue, onCleanup) => {
    const controller = new AbortController();
    let active = true;

    onCleanup(() => {
      active = false;
      controller.abort();
    });

    const next = await load(value, { signal: controller.signal });
    if (active) result.value = next;
  },
);
</script>

配置(Vite+)

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

export default defineConfig({}).withVue({
  linter: { preset: "incremental", crossFile: true,
    rules: { "croquis/cf/watcheffect-async": "warn" },
  },
});
vp run lint

相关页面

公开说明

诊断实现

跨文件规则索引