Could you get a doctorate based solely on a thesis written in your free time?
Just write your paper, as long as the writing does not distract you from your undergrad studies. If the paper has merit, you may be able to present it at a colloquium of your university, at a workshop, or even at a conference. If you put some more work into it and are lucky, you might eventually be able to publish it in a journal. Certainly, your paper will open up more questions than it answers. Now you have a research trajectory that you can follow up and that may lead to a PhD thesis, based on but surely not limited to your first paper.

In other words: There is no reason why you should not start to work on your PhD topic already as an undergraduate, but it seems to me that you underestimate the time and work it takes to finish the PhD. And since PhDs require a lot of work, there are PhD programs, which facilitate the process and in which most PhDs are actually produced. In that sense, writing your PhD outside of the designated framework is a bit like digging a well with a spoon. It can be done, but it is not too efficient. On top of that (as others have said already), at many institutions, the written thesis is only one requirement among others to be awarded a title.