首先,这是我得到的完整错误。
@firebase/firestore: Firestore (8.1.1): Host has been set in both settings() and useEmulator(), emulator host will be used
Error [FirebaseError]: Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.
这就是我初始化模拟器的方式
const db = app.firestore();
const auth = firebase.auth();
if (process.env.NODE_ENV === 'development') {
db.useEmulator('localhost', 8888);
firebase.auth().useEmulator('http://localhost:9099/');
}
当我第一次启动应用程序时,项目正在运行 nextjs 一切都按预期运行,但是在 next.js 页面之间刷新或导航后,我突然收到此错误。我必须杀死终端并重新开始,这很烦人我不知道 next.js 服务器是否运行 if (process.env.NODE_ENV === 'development')
代码多次,这可能是导致此错误的原因,如果在这种情况下如何避免在已有模拟器时设置新模拟器。还是与 firebase 模拟器相关的错误?
最佳答案
NextJs 正在热加载网页,并且 xxx.useEmulator(...)
为同一个浏览器实例调用两次。
在幕后,Firebase 库使用对当前应用程序的全局引用,从库的角度来看,您尝试将其初始化两次或更多次。
您可以使用以下代码重现此问题:
const db = app.firestore();
db.useEmulator('localhost', 8888);
db.useEmulator('localhost', 8888); // raises error
我发现的唯一解决方法是使用 window 对象来保存一个标志(如果它已被初始化),但您还必须处理 SSR 的边缘情况。const db = app.firestore();
if(typeof window === 'undefined' || !window['_init']) {
db.useEmulator('localhost', 8888);
if(typeof window !== 'undefined') {
window['_init'] = true;
}
}
这不是上面最优雅的代码,但它修复了错误。关键是要知道热重载是问题所在,Firebase 应该只配置一次。
关于reactjs - Firebase Firestore 模拟器错误 `Host has been set in both settings() and useEmulator(), emulator host will be used`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65066963/