You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中PouchDB同步报错:Can't find variable: btoa

问题排查与解决:React Native PouchDB同步报错"Can't find variable: btoa"

核心原因

React Native 环境不支持浏览器原生的 btoa() 函数,而PouchDB同步时需要该函数处理Base64编码(比如CouchDB认证信息),因此触发此错误。

解决方案步骤

1. 补全全局btoa/atob方法

修改你的shim.ts文件,添加这两个函数的实现:

// shim.ts
global.btoa = function (str: string) {
  return Buffer.from(str).toString('base64');
};

global.atob = function (b64Str: string) {
  return Buffer.from(b64Str, 'base64').toString();
};

关键:确保这个shim文件在PouchDB被导入前加载,比如在项目入口文件(index.tsx/App.tsx)最顶部引入:

import './shim.ts';

2. 检查PouchDB同步配置

确认pouchDB.ts中同步逻辑的CouchDB地址与认证信息正确:

// pouchDB.ts示例
import PouchDB from 'pouchdb-react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

PouchDB.plugin(require('pouchdb-adapter-asyncstorage').default);
export const localDb = new PouchDB('local-db', { adapter: 'asyncstorage' });

// 带认证的远程数据库配置
export const getRemoteDb = () => {
  return new PouchDB('http://admin:adminpass@localhost:5984/remote-db', {
    auth: {
      username: 'admin',
      password: 'adminpass'
    }
  });
};

3. 验证Docker部署的CouchDB

检查你的Docker Compose配置,确保端口映射与权限设置正确:

# docker-compose.yml示例
version: '3'
services:
  couchdb:
    image: couchdb:latest
    ports:
      - "5984:5984"
    environment:
      - COUCHDB_USER=admin
      - COUCHDB_PASSWORD=adminpass
    volumes:
      - couchdb_data:/opt/couchdb/data
volumes:
  couchdb_data:

启动后访问http://localhost:5984/_utils,确认CouchDB正常运行,且目标同步数据库已创建。

4. 调整同步函数的错误捕获

修改syncPouchTest函数,确保逻辑正确且错误信息可追踪:

// syncPouchTest示例
import { localDb, getRemoteDb } from './pouchDB';

export const syncPouchTest = async () => {
  try {
    const remoteDb = getRemoteDb();
    const syncResult = await localDb.sync(remoteDb, {
      live: false,
      retry: true
    });
    console.log('同步完成:', syncResult);
    return syncResult;
  } catch (error) {
    console.error('同步失败详情:', error);
    throw error;
  }
};

额外检查点

  • 确认pouchdb-react-native版本与React Native 0.68.2兼容,建议使用^8.0.0版本
  • 确保@react-native-async-storage/async-storage已正确安装并链接

内容的提问来源于stack exchange,提问作者Abdiel49

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:01:13