YMFE/yapi · error

context.hostname 不能被赋值

Error message

context.hostname 不能被赋值

What it means

context.hostname in the test-script sandbox is a read-only getter derived from the request URL. The setter exists solely to throw, preventing scripts from mutating the resolved host.

Solutions

  1. Delete the hostname assignment from the script
  2. Change the request URL/environment at the case level instead of in the script
  3. Only read context.hostname in scripts

Example fix

// before
context.hostname = 'staging.api.com';
// after
// configure environment host in the case, then read it
const host = context.hostname;
Defensive patterns

Strategy: type-guard

Validate before calling

if (context.hostname !== expectedHost) console.warn('unexpected host; reconfigure environment instead of assigning');

Type guard

function isReadOnlyCtxProp(obj, key){ const d = Object.getOwnPropertyDescriptor(obj, key); return !!d && d.get && d.set && d.set.toString().includes('throw'); }

Try / catch

try {
  context.hostname = host;
} catch (e) {
  console.warn('hostname is derived from request URL and cannot be set');
}

Prevention

When it happens

Trigger: A case script executes context.hostname = 'api.example.com' during test/assert execution.

Common situations: Attempting to switch environments from inside a script; copying Postman snippets that mutate context; misunderstand that sandbox context is read-only.

Related errors


AI-assisted analysis of YMFE/yapi@59bade3a8a (2026-08-29). Data as JSON: /api/errors/b30ae4f4dc5bdc7c. Report an issue: GitHub.

Appendix: source

Thrown at common/postmanLib.js:266

async function crossRequest(defaultOptions, preScript, afterScript, commonContext = {}) {
  let options = Object.assign({}, defaultOptions);
  const taskId = options.taskId || Math.random() + '';
  let urlObj = URL.parse(options.url, true),
    query = {};
  query = Object.assign(query, urlObj.query);
  let context = {
    isNode,
    get href() {
      return urlObj.href;
    },
    set href(val) {
      throw new Error('context.href 不能被赋值');
    },
    get hostname() {
      return urlObj.hostname;
    },
    set hostname(val) {
      throw new Error('context.hostname 不能被赋值');
    },

    get caseId() {
      return options.caseId;
    },

    set caseId(val) {
      throw new Error('context.caseId 不能被赋值');
    },

    method: options.method,
    pathname: urlObj.pathname,
    query: query,
    requestHeader: options.headers || {},
    requestBody: options.data,
    promise: false,
    storage: await getStorage(taskId)
  };

View on GitHub (pinned to 59bade3a8a)