Vize

vize:croquis/cf/watcheffect-async

非同期の watchEffect で無効になった処理を中止し、古い応答を反映しないようにします。

既定の重大度 自動修正 オプション
error なし。関連ファイルを確認して修正してください コード固有のオプションはありません。対応済みの CLI の診断は、重大度を変更できます

適用範囲: 解析対象のコンポーネント構成と、下記に示す対応済みの情報

範囲と制約

この例の非同期の watchEffect には、無効化時のクリーンアップや古い応答を防ぐ処理がありません。Vue の watchEffect はクリーンアップを扱えます。良い例では watch で監視対象を明示し、無効化された処理を中止します。

共通のプロジェクト ファイル

以下のファイルは、悪い例・良い例の両方で変更せずに使います。プロジェクトには Vue をインストールし、例で import している場合は 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 で、暗黙の依存関係の収集と await によるリクエストの待機を行っています。無効化後に届く応答への対処はありません。

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

関連ページ

公開の説明

生成元

ファイル間ルール一覧