Nuxt3 useFetch 水合已完成,但包含不匹配错误

问题描述 投票:0回答:1

如果我在 onMounted 上使用 CustomFetch 并重新加载页面,则会出现错误“水合已完成但包含不匹配”。出现。但是,如果我重定向到该页面,则 useCustomFetch 可以正常工作,不会出现错误。

// useCustomFetch.ts
import { useFetch } from '#app';

export async function useCustomFetch(url: string, options: any, showLoading: boolean = false) {
    if (!process.server) {
        console.log("Not Server side called APIs");
    }
    console.log("called APIs");

    if (typeof window === 'undefined') return;

    console.log("Start APIs");

    try {
        const { data, error } = await useFetch(url, options);

        if (showLoading) {
            console.log("Showing loading...");
        }

        if (showLoading) {
            console.log("Closing loading...");
        }

        const response = data.value;
        const responseError = error.value;

        if (responseError) {
            console.error("Fetch error: ", responseError);
            return null;
        }

        return response;
    } catch (err) {
        console.error("Error in useCustomFetch:", err);
        throw err;
    }
}

这是从浏览器打印出来的:

browser.mjs:44  Not Server side called APIs
browser.mjs:44  called APIs
browser.mjs:44  Start APIs
browser.mjs:44  error Hydration completed but contains mismatches.
    log @ browser.mjs:44
    _log @ core.mjs:381
    resolveLog @ core.mjs:349
    _logFn @ core.mjs:377
    (anonymous) @ core.mjs:306
    hydrate2 @ runtime-core.esm-bundler.js:4641
    mount @ runtime-core.esm-bundler.js:3919
    app.mount @ runtime-dom.esm-bundler.js:1530
    initApp @ entry.js:56
    await in initApp (async)
    (anonymous) @ entry.js:67
    Show 5 more frames
    Show less
browser.mjs:44  Showing loading...
browser.mjs:44  Closing loading...

这是我使用CustomFetch的页面,我已经确保它在客户端被调用。

// some page/xxx.vue

const getInventoryData = async () => {
    try {
        inventoryData.value = await useCustomFetch('/api/inventory/', {
            method: 'GET',
        }, true);
    } catch (err: any) {
        error.value = err;
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    getInventoryData();
});

为什么我需要使用自定义获取是我想在 API 调用和 API 结果期间加载弹出窗口和其他通知。否则我需要在每个 useFetch 上复制并粘贴所有设置。

纯设置后一切正常(不使用 onMounted)

const {data, error} = await useFetch('/api/inventory/inventory/', {
    method: 'GET',
});

console.log(data.value)
nuxt.js nuxtjs3 nuxt3 usefetch
1个回答
0
投票

我发现问题了。 首先,我的自定义获取确实包含一些客户端内容,例如 swal 和 toast。 因此,如果不在 onMounted 内部,它就无法运行。 其次,我发现一些关于使用useFetch返回null的帖子,这似乎是nodeJS的一个错误。我使用的是 18.19.0,升级到 18.20.2 (2024/05/16),useFetch 确实返回值不为空。

// NOT inside onMounted
const {data, error} = await useFetch('/api/inventory/inventory/', {
    method: 'GET',
});

console.log(data.value)  // Not null 
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.