文章

next.js中使用zustand引入第三方库报错self is not defined

nextjs 14.0.4使用zustand引用一些第三方的库时出现的self is not defined 问题

比如useExamplePKGStore

import examplePKG from "example";
const useExamplePKGStore = create((set) => ({
	data: null;
	init: ()=> {
		set({ data: new examplePKG() })
	}
}))

这时候在next的页面中引用

任意的page.js

import useExamplePKGStore from '@/app/store/useExamplePKGStore';
import { useEffect } from 'react';
const Page = () => {
	const { init } = useExamplePKGStore()
	useEffect(()=>{
		init()
    }, [])
   return <div>test</div>	
}

这时候会报self is not defined

useExamplePKGStore.js 中改为

import examplePKG from "example";
const useExamplePKGStore = create((set) => ({
	data: null;
	init: ()=> {
       import("example").then((examplePKG) => {
		   set({ data: new examplePKG() })
       });
	}
}))

即可解决组件中报self is not defined 的问题

许可协议:  CC BY 4.0