问题描述
我正在使用Svelte和URQL。
除了在format: 'esm'
中创建rollup.config.js
之外,我正在使用svelte example in your packages folder here。
当我在代码中使用import('./Component.svelte')
时,我的汇总已经将我的最终分发包分成多个代码。
我很难做的是异步初始化urql,如下所示:
import { initClient,dedupExchange,fetchExchange } from '@urql/svelte'
import { cacheExchange } from "@urql/exchange-graphcache";
const exchanges = [
cacheExchange({
resolvers: { /*... my resolvers*/ },schema // I need this async,something like: await import('./schema').then(result => result.default)
}),fetchExchange
]
export function initURQL () {
initClient({
url: 'http://localhost/graphql',exchanges
})
}
如果我使用类似的东西:
export async function initURQL () {
const schema = await import('./schema.json').default
const exchanges = [
cacheExchange({
resolvers: {},schema
}),fetchExchange
]
initClient({
url: 'http://localhost/graphql',exchanges
})
}`
并从App.svelte
用;(async () => await initURQL())()
调用它会给我错误:
Uncaught (in promise) Error: Function called outside component initialization
我该如何解决?
解决方法
我没有使用URQL,但是我也遇到了这个错误。
不幸的是,您无法异步调用getContext
或setContext
(这是initClient
中urql/packages/svelte-urql/src/context.ts
的调用)。
https://svelte.dev/docs#setContext:
就像生命周期函数一样,必须在组件初始化期间调用它。
https://github.com/timhall/svelte-apollo/issues/9#issuecomment-646184888回答了一个非常类似的问题,并希望为您指出一个合适的解决方法:
这种情况发生在getClient和setClient上,因为它很苗条 仅在组件初始化时可用的上下文 (构造),并且不能在事件处理程序中。看到:答案 Svelte user registration issue with setting store value 最有可能发生的事情是您正在异步调用它 事件su作为on:click,onMount,onDestroy(不可用)时。 解决方案是将客户端存储为上下文中的商店 按照 https://svelte.dev/tutorial/context-api。
通常它应该看起来像这样:
setClient(writable(apolloClient)); let client getClient().subscribe((_client) => client = _client);