问题描述

  1. vue3中封装了个http请求,然后想绑定在vue的全局对象上去,核心代码如下。然后在运行的时候就报错了,报错信息如下:<br />Error:"类型“ComponentInternalInstance | null”上不存在属性“proxy”。"
  1. import Axios from './utils/axios.js'
  2. app.config.globalProperties.$http = Axios
  3. import { getCurrentInstance } from "vue";
  4. const { proxy } = getCurrentInstance();
  5. proxy.$http.get("/slardar/sdk_setting?bid=juejin_web").then((res: any) => {
  6. console.log(res, "res");
  7. });

问题分析: 这里是由于可能会存在null情况,添加断言试试。

  1. import { getCurrentInstance, ComponentInternalInstance } from "vue";
  2. const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  3. proxy.$http.get("/slardar/sdk_setting?bid=juejin_web").then((res: any) => {
  4. console.log(res, "res");
  5. });

未曾想到,这段代码又引发了新问题: 对象可能为 “null”。