The problem happens whenever a \label depends on the context of the item which is to be labelled. In this case, pgfplots provides its own label functionality. This, in turn, boils down to the standard LaTeX \label command eventually.
And the standard LaTeX \label results in \write{....} (to write something to the .aux file).
This \write is the "problem", combined with the spy libary: the spy library collects all its stuff into a TeX box and typesets that twice. A \write is also part of that box, and will be executed everytime the box is used (from what I know and see). A solution would be to use \immediate\write instead of \write in this context.
** EDIT: ** this answer was RASH; its suggested solution below might
BREAK links:
while my analysis above seems to be correct, the proposed solution below is probably of less use than I claimed. When it was later yesterday night, I did not think about the most important question:
why has someone deferred the write!? Of course, he did so because the label mechanism is used to establish a connection between the labelled item and the reference. Typically, this requires the page number where the labelled item is typeset. And this, in turn, can only be retrieved using deferred write.
Perhaps you can still use my hack for pgfplots because there, you do not want to know the page number - you want to have the small legend image. That should do. However, my hack might (?) break hyperrefs.
But the solution is clearly wrong for any other \label because it will destroy page number information for larger documents.
Use it on your own risk.
You can replace the \write functionality temporarily as in the following example - and it will work (for every \label, not just for pgfplots):
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usetikzlibrary{spy}
\newenvironment{writereplace}{%
\begingroup
\let\writeold=\write
\def\write{\immediate\writeold}%
}{%
\endgroup
}%
\begin{document}
\begin{writereplace}
\begin{tikzpicture}[spy using outlines={circle, magnification=2, size=1cm,
connect spies}]
\begin{axis}
\addplot{x^2 - x +4};\label{plot:curve}
\end{axis}
\begin{scope}
\spy[green!30!black,size=1cm] on (3,.85) in node [fill=white] at (4,2);
\end{scope}
\end{tikzpicture}
\end{writereplace}
\ref{plot:curve}
\end{document}
\labelcommand within thespyscope? – Jake Jun 20 '12 at 15:53\def\label#1{}). I guess we need to dive deeper into the pgfplots label handeling mechanism... – Martin H Jun 20 '12 at 17:11