I have not read much fanfiction myself, but I am aware of it. And fanfiction has been around for a really really long time.
Both my older sister (the research scientist in my family) and my mother buy media fanzines to sell on eBay. I know they have a lot of Star Trek, but also pretty lots of other TV shows and movies, too. Many of these fanzines fetch a fair price since they've been out of print for a long time, that is, predating what's online. A lot of the zines are from the 70s and people who read them can't get enough of them, despite the zillions of stories available online.
I equate fanzines/fanfiction with fanfilms you can view online. People make their own movies based on Star Trek or Star Wars and share them with the world. George Lucas is somewhere on record as saying he doesn't mind SW-based fanfilms because they help keep the spirit and interest alive in Star Wars, plus as long as nobody is asking for money, then it's okay. Same with Star Trek. Paramount is okay with fanfilms as long as no money is exchanged.
Fanzines are sold, however. How is that legal? I have no idea. But fanfiction, both good and bad, is available for free online.
My personal feeling is that fanfiction can help a writer write. You can learn a lot by writing just about anything, and it's good practice. As is stated above, some fanfiction writers have gone on to commercial publication. They honed their talents writing stories based on existing programs. Then, with practice, they honed their craft and got published. Nothing wrong with that, IMO.