Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[useFetch] Component is already mounted, please use $fetch instead. See https://nuxt.com/docs/getting-started/data-fetching #27242

Closed
bbhxwl opened this issue May 16, 2024 · 13 comments

Comments

@bbhxwl
Copy link

bbhxwl commented May 16, 2024

Although it can be used, there are warnings. Why? Can't I keep using useFetch?

import type {UseFetchOptions} from "#app";
import type {Ref} from "vue";
import type {SearchParameters} from "ofetch";

const request = async <T = any>(url: any, options: any) => {
    const config = useRuntimeConfig();
    //设置url
    options.baseURL=config.public.apiBase
    let token = useCookie("manageToken")
    let customHeaders: { "Content-Type": string, Authorization?: string } = {"Content-Type": "application/json"}
    const res=await useFetch<T>(url, {headers: customHeaders,...options})
    if(process.client){
        if(res.error&&res.error.value){
            ElNotification({
                title: '系统错误提示',
                message: res.error.value.message,
                type: 'error',
                appendTo: document.body,
                zIndex: 9999
            })
        }
        else if (res.data.value&&(res.data.value as any).Msg) {
            if((res.data.value as any).Code===0){
                ElNotification({
                    title: '系统提示',
                    message: (res.data.value as any).Msg,
                    type: 'success',
                    appendTo: document.body,
                    zIndex: 9999
                })
            }
            else{
                ElNotification({
                    title: '错误提示',
                    message: (res.data.value as any).Msg,
                    type: 'error',
                    appendTo: document.body,
                    zIndex: 9999
                })
            }
        }
    }

    return res
};
type ResponseType<T = any> = T extends undefined ? CommonResponse<any> : CommonResponse<T>;

export const http = {
    get: <T = any>(url: Ref<string>|string, query?: SearchParameters, opts?: UseFetchOptions<T>) => {
        return request<T>(url, {...opts,...{method: 'GET', query}});
    },
    post: <T = undefined>(url: Ref<string>|string, body?: RequestInit["body"] | Record<string, any>, opts?: UseFetchOptions<ResponseType<T>>) => {
        return request<ResponseType<T>>(url, {...opts,...{method: 'POST', body}});
    },
    put: <T = undefined>(url: Ref<string>|string, body?: RequestInit["body"] | Record<string, any>, opts?: UseFetchOptions<ResponseType<T>>) => {
        return request<ResponseType<T>>(url, {...opts,...{method: 'PUT', body}});
    },
    postGetList: (url: Ref<string>|string, body?: RequestInit["body"] | Record<string, any>, opts?: UseFetchOptions<ResponseType<CommonResponseGetList>>) => {
        return request<CommonResponseGetList>(url, {...opts,...{method: 'POST', body}});
    },
}

Copy link
Contributor

Would you be able to provide a reproduction? 🙏

More info

Why do I need to provide a reproduction?

Reproductions make it possible for us to triage and fix issues quickly with a relatively small team. It helps us discover the source of the problem, and also can reveal assumptions you or we might be making.

What will happen?

If you've provided a reproduction, we'll remove the label and try to reproduce the issue. If we can, we'll mark it as a bug and prioritize it based on its severity and how many people we think it might affect.

If needs reproduction labeled issues don't receive any substantial activity (e.g., new comments featuring a reproduction link), we'll close them. That's not because we don't care! At any point, feel free to comment with a reproduction and we'll reopen it.

How can I create a reproduction?

We have a couple of templates for starting with a minimal reproduction:

👉 https://stackblitz.com/github/nuxt/starter/tree/v3-stackblitz
👉 https://codesandbox.io/s/github/nuxt/starter/v3-codesandbox

A public GitHub repository is also perfect. 👌

Please ensure that the reproduction is as minimal as possible. See more details in our guide.

You might also find these other articles interesting and/or helpful:

@huang-julien
Copy link
Member

Hello, that's because you're probably calling it outside a nuxt setup or component setup hook. see https://www.youtube.com/watch?v=njsGVmcWviY

@huang-julien huang-julien closed this as not planned Won't fix, can't repro, duplicate, stale May 16, 2024
@bbhxwl
Copy link
Author

bbhxwl commented May 16, 2024

Hello, that's because you're probably calling it outside a nuxt setup or component setup hook. see https://www.youtube.com/watch?v=njsGVmcWviY

Can't I call it with a method? My English is not good and I can't understand the video. Can you describe it in text? Can't I call useFetch as a method?

@huang-julien
Copy link
Member

useFetch is a composable, it means that it is meant to be called in a setup function (nuxt or vue).
If you need to do any calls outside/after a component's setup function being called, you can use $fetch or the native fetch.

@bbhxwl
Copy link
Author

bbhxwl commented May 17, 2024

useFetch is a composable, it means that it is meant to be called in a setup function (nuxt or vue). If you need to do any calls outside/after a component's setup function being called, you can use $fetch or the native fetch.

I did this, and a warning will appear in the btnClick method.

image

@bbhxwl
Copy link
Author

bbhxwl commented May 17, 2024

Isn't there a universal method?

@Nisekoi5
Copy link

Nisekoi5 commented May 17, 2024

Requests initiated only on the client side should use $fetch
https://www.youtube.com/watch?v=njsGVmcWviY


You can continue to use it, it will only display warnings, but problems may occur in some scenarios.
It is recommended to use $fetch instead. For details, you can check the youtube video link I sent.

@bbhxwl
Copy link
Author

bbhxwl commented May 17, 2024

Requests initiated only on the client side should use $fetch https://www.youtube.com/watch?v=njsGVmcWviY

You can continue to use it, it will only display warnings, but problems may occur in some scenarios. It is recommended to use $fetch instead. For details, you can check the youtube video link I sent.

Do I need to use two different methods for the server and client?

@bbhxwl
Copy link
Author

bbhxwl commented May 17, 2024

Requests initiated only on the client side should use $fetch https://www.youtube.com/watch?v=njsGVmcWviY

You can continue to use it, it will only display warnings, but problems may occur in some scenarios. It is recommended to use $fetch instead. For details, you can check the youtube video link I sent.

I am not good at English and cannot translate videos.

@Nisekoi5
Copy link

Requests initiated only on the client side should use $fetch https://www.youtube.com/watch?v=njsGVmcWviY
You can continue to use it, it will only display warnings, but problems may occur in some scenarios. It is recommended to use $fetch instead. For details, you can check the youtube video link I sent.

Do I need to use two different methods for the server and client?

Yes, use $fetch if this call is only for client requests
If you need to initiate a request on both the server and client. You can use the execute/refresh method returned by useFetch to re-initiate the request. Instead of calling a new useFetch


是的,如果这个调用只在客户端请求就使用 $fetch
如果在服务端和客户端都需要发起请求。则可以使用 useFetch 返回的 execute/refresh 方法来重新发起请求。而不是重新调用一次新的 useFetch

此外youtube有翻译字幕功能

@bbhxwl
Copy link
Author

bbhxwl commented May 17, 2024

useFetch

仅在客户端发起的请求应该使用 $fetch https://www.youtube.com/watch?v=njsGVmcWviY
可以继续使用它,它只会显示警告,但在某些场景下可能会出现问题。建议使用 $fetch 代替。详情可以查看我发的youtube视频链接。

我需要为服务器和客户端使用两种不同的方法吗?

$fetch是的,如果此调用仅针对客户端请求,则使用 如果您需要在服务器和客户端上都发起请求。您可以使用execute/refresh返回的方法useFetch重新发起请求。而不是调用一个新的useFetch

是的,如果这个调用只在客户端请求就使用,$fetch 如果在服务端并且客户端都需要发起请求。则可以使用useFetch返回的 execute/refresh方法来重新发起请求。而不是重新调用一次新的useFetch

另外youtube有翻译字幕功能

I am currently only using useFetch, not refresh, and there are no errors. Will there be any unexpected issues?

@Nisekoi5
Copy link

I am currently only using useFetch, not refresh, and there are no errors. Will there be any unexpected issues?

Not sure, it depends on the usage scenario

@KyleXie
Copy link

KyleXie commented May 22, 2024

useFetch is a composable, it means that it is meant to be called in a setup function (nuxt or vue). If you need to do any calls outside/after a component's setup function being called, you can use $fetch or the native fetch.

I did this, and a warning will appear in the btnClick method.

image

你还可以这样:

<script setup lang="ts">
const { refresh } = useFetch('test');

function btnClick() {
    refresh();
}
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants