SvelteKit导出函数中无法访问stores的问题求助
问题原因
$session 是Svelte专属的自动订阅语法糖,仅在Svelte组件的上下文(如组件内部的<script>标签)中生效。普通JS模块(你导出getSession的文件)不会被Svelte编译器处理,因此无法识别$前缀的订阅语法,导致referenceError。
解决方案
你需要用svelte/store提供的工具函数来获取store的当前值,而非依赖组件专属的语法糖。以下是两种可行方案:
方案1:使用get函数(推荐,适合一次性获取值)
从svelte/store导入get函数,它可以同步获取store的当前值:
import { session } from '$stores/global'; import { v4 as uuid } from 'uuid'; import { get } from 'svelte/store'; // 导入get工具函数 export const getSession = () => { const currentSession = get(session); if (currentSession) { return currentSession; } else { const sessionId = uuid(); session.set(sessionId); // 同步更新localStorage,避免刷新后丢失session if (typeof window !== 'undefined') { localStorage.setItem('session', sessionId); } return sessionId; } };
方案2:手动订阅store
通过subscribe方法订阅store,获取值后立即取消订阅(避免内存泄漏):
import { session } from '$stores/global'; import { v4 as uuid } from 'uuid'; export const getSession = () => { let currentSession; // 订阅store获取当前值 const unsubscribe = session.subscribe(value => { currentSession = value; }); unsubscribe(); // 立即取消订阅 if (currentSession) { return currentSession; } else { const sessionId = uuid(); session.set(sessionId); if (typeof window !== 'undefined') { localStorage.setItem('session', sessionId); } return sessionId; } };
补充说明
你之前尝试的.get()方法出错,是因为writable store本身没有get方法——get是独立的工具函数,需要从svelte/store单独导入,而非直接调用store实例的方法。
另外,原store初始化时从localStorage取值,但set操作不会自动同步到localStorage,所以需要手动添加localStorage.setItem逻辑,确保刷新页面后session能保留。
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

