八、常见问题与解决方案
🌐
在使用 Claude Code 的过程中,你可能会遇到一些常见问题。本章节收集了最常见的问题及其解决方案,帮助你快速排除故障。
8.1 安装问题
Q1: npm install 失败
问题:
代码块
Bash
npm ERR! code EACCES
npm ERR! syscall access
解决方案:
代码块
Bash
# 方式1: 使用 sudo (macOS/Linux)
sudo npm install -g @anthropic-ai/claude-code
# 方式2: 修改 npm 全局目录mkdir ~/.npm-global
npm config set prefix '/.npm-global'export PATH=/.npm-global/bin:$PATH
npm install -g @anthropic-ai/claude-code
# 方式3: 使用 nvm (推荐)
nvm install --lts
npm install -g @anthropic-ai/claude-code
Q2: claude 命令未找到
问题:
代码块
Bash
bash: claude: command not found
解决方案:
代码块
Bash
# 检查 npm 全局路径
npm config get prefix
# 添加到 PATHexport PATH=$(npm config get prefix)/bin:$PATH# 永久配置echo 'export PATH=$(npm config get prefix)/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
8.2 配置问题
Q3: 模型配置不生效
问题:配置后仍显示默认模型
解决方案:
代码块
Bash
# 1. 验证环境变量echo $ANTHROPIC_BASE_URLecho $ANTHROPIC_AUTH_TOKENecho $ANTHROPIC_MODEL# 2. 重新启动终端# 配置环境变量后必须重启终端才能生效# 3. 使用 claude /status 检查
claude
/status
# 4. 手动设置(临时)
claude
/model
# 选择第4个(自定义模型)
Q4: MCP 服务器无法连接
问题:
代码块
Bash
Error: MCP server 'chrome-devtools' failed to start
解决方案:
代码块
Bash
# 1. 检查 MCP 状态
claude
/mcp
# 2. 测试连接
claude mcp test chrome-devtools
# 3. 重新安装
claude mcp remove chrome-devtools
claude mcp add chrome-devtools npx chrome-devtools-mcp@latest
# 4. 检查网络
npx chrome-devtools-mcp@latest --version
# 5. 查看日志
claude /doctor
8.3 使用问题
Q5: 上下文超出限制
问题:
代码块
SQL
Context exceeded: Request too large
解决方案:
代码块
Bash
# 1. 查看上下文使用
/context
# 2. 使用 compact 保留摘要
/compact "保留项目背景和当前任务"# 3. 使用 clear 清空历史
/clear
Q6: 代码生成质量差
问题:生成的代码不符合项目规范
解决方案:
代码块
Bash
# 1. 完善 CLAUDE.md# 在 CLAUDE.md 中明确代码规范# 2. 使用 Plan 模式
Shift+Tab × 2
# 让 Claude 先理解项目再编写代码# 3. 提供示例# 这是符合规范的代码示例:
@src/good-example.ts
# 请参照这个风格编写新功能# 4. 明确要求
请编写符合以下规范的代码:
- 使用 TypeScript 严格模式
- 遵循项目命名规范
- 包含完整的错误处理
- 添加必要的注释
8.4 性能问题
Q7: 响应速度慢
问题:Claude Code 响应延迟高
解决方案:
代码块
Bash
# 1. 检查网络
ping api.anthropic.com
# 2. 切换更快的模型
/model
# 选择 Haiku 4.5(最快) 或国产模型# 3. 优化提示词# 避免冗长的提示词,直接说明需求# 4. 减少上下文
/context
# 如果接近 100%,使用 /compact 清理# 5. 使用本地模型(如果有)export ANTHROPIC_BASE_URL=http://localhost:8000
Q8: Token 消耗过快
问题:费用增长过快
解决方案:
代码块
Bash
# 1. 监控费用
/cost
# 2. 定期 compact
/compact "保留关键信息"# 3. 新任务先 clear
/clear
# 4. 使用更便宜的模型# Haiku < Sonnet < Opus# 国产模型(更便宜)# 5. 优化工作流# 避免反复修改,一次性明确需求
8.5 调试技巧
启用调试模式
代码块
Bash
# 设置环境变量export CLAUDE_DEBUG=trueexport CLAUDE_LOG_LEVEL=debug
# 启动 Claude Code
claude
# 查看日志tail -f ~/.claude/logs/claude.log
使用 /doctor 诊断
代码块
Bash
claude
/doctor
检查项:
•
✅ 安装版本
•
✅ 配置文件
•
✅ API 连接
•
✅ MCP 服务器
•
✅ 权限设置
•
✅ 环境变量